package com.quanyan.place.wrapper.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.enums.CouponOrderType;
import com.quanyan.assets.request.ReqCoupon;
import com.quanyan.assets.request.ReqRuleDetail;
import com.quanyan.assets.response.RespCoupon;
import com.quanyan.assets.response.RespOrderCoupon;
import com.quanyan.assets.response.RespRuleDetail;
import com.quanyan.assets.service.CouponService;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.enums.PlatformTypeEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.*;
import com.quanyan.messagepush.entity.*;
import com.quanyan.messagepush.enums.BoxName;
import com.quanyan.messagepush.enums.BoxType;
import com.quanyan.messagepush.enums.IdType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.orderpay.request.*;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.RefundStatusEnum;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.component.MerchantClientPayType;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.apireq.*;
import com.quanyan.place.entity.apiresp.*;
import com.quanyan.place.entity.dto.OrderHistoryDTO;
import com.quanyan.place.entity.dto.OrderItemCostDTO;
import com.quanyan.place.entity.vo.PlacePrintVo;
import com.quanyan.place.entity.vo.PlaceTicketPushOrderVo;
import com.quanyan.place.entity.vo.TicketPushOrderVo;
import com.quanyan.place.entity.vo.UnitSalePlan;
import com.quanyan.place.enums.PlaceErrorCodeEnum;
import com.quanyan.place.mapper.*;
import com.quanyan.place.service.*;
import com.quanyan.place.utils.PlaceOrderUtil;
import com.quanyan.place.wrapper.PlaceMemberWrapper;
import com.quanyan.place.wrapper.PlaceOrderAdminServiceWrapper;
import com.quanyan.sms.service.SmsService;
import com.quanyan.user.request.ReqUserInvite;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.response.RespUserInvite;
import com.quanyan.user.serviceFacade.UserInviteServiceFacade;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sms.SmsApi;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_BASE;
import static com.quanyan.place.constants.PlaceConstants.UNIT_TYPE_COMBINE;

/**
 * 
 * @des
 * @author tim
 * @date 2017年5月8日
 */
@Service("placeOrderAdminServiceWrapperImpl")
public class PlaceOrderAdminServiceWrapperImpl implements PlaceOrderAdminServiceWrapper {
    private static final Logger logger = LoggerFactory.getLogger(PlaceOrderAdminServiceWrapperImpl.class);

    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;
    @Autowired
    TbBizPlaceUnitMapper placeUnitMapper;
    @Autowired
    TbBizPlaceAttachMapper tbBizPlaceAttachMapper;
    @Autowired
    TbPlaceImageMapper tbPlaceImageMapper;
    @Autowired
    PlaceUnitMapper placeUnitListMapper;
    @Autowired
    PlaceAttachMapper placeAttachMapper;
    @Autowired
    TbBizPlaceUnitTimeMapper tbBizPlaceUnitTimeMapper;
    @Autowired
    TbBizPlaceCategoryMapper tbBizPlaceCategoryMapper;
    @Autowired
    PlaceClient placeClient;
    @Autowired
    TbBizPlaceUnitSalePlanMapper tbBizPlaceUnitSalePlanMapper;

    @Autowired
    TbBizPlaceOrderMapper tbBizPlaceOrderMapper;

    @Autowired
    TbBizPlaceOrderItemMapper tbBizPlaceOrderItemMapper;

    @Autowired
    PlaceUnitSalePlanMapper placeUnitSalePlanMapper;

    @Autowired
    TbBizPlaceOrderManagerMapper tbBizPlaceOrderManagerMapper;

    @Autowired
    OrderPayService orderPayService;

    @Autowired
    TbBizPlacePayItemMapper tbBizPlacePayItemMapper;

    @Autowired
    UserServiceFacade userServiceFacade;

    @Autowired
    UserAssetsService userAssetsService;

    @Autowired
    PlaceRedisTemplate placeRedisTemplate;

    @Autowired
    TbBizPlaceRuleMapper tbBizPlaceRuleMapper;

    @Autowired
    UserService userService;

    @Autowired
    ISearchService searchService;

    @Autowired
    PlaceMapper placeMapper;


    @Value("${c.service.url}")
    public String cAddress;

    @Autowired
    UserInviteServiceFacade userInviteServiceFacade;

    @Autowired
    ClubOpenService clubOpenService;

    @Autowired
    BaseService baseService;

    @Autowired
    IBaseService iBaseService;

    @Autowired
    PlaceMessageService placeMessageService;

    @Autowired
    private PlaceTicketService placeTicketService;

    @Autowired
    private PlaceOrderSetterService placeOrderSetterService;

    @Value("${notify.url.payUrl}")
    private String payUrl;

    @Value("${notify.url.refundUrl}")
    private String refundUrl;

    @Value("${notify.url.exception.refundUrl}")
    private String exceptionRefundUrl;

    @Value("${notify.url.closeOrderUrl}")
    private String closeOrderUrl;

    @Value("${place.share.url}")
    private String placeShareUrl;

    @Value("${place.escape.clause.url}")
    private String placeEscapeClauseUrl;

    @Value("${notify.url.supplierExtractUrl}")
    private String supplierExtractUrl;

    @Autowired
    MqPlaceProductWrapperImpl mqPlaceProductWrapper;

    @Autowired
    PlaceMemberService placeMemberService;

    @Autowired
    TbBizPlaceMemberOpHistoryMapper tbBizPlaceMemberOpHistoryMapper;

    @Autowired
    SmsService smsService;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    com.quanyan.place.biz.SmsService  placeSmsService;

    @Autowired
    private TbBusinessLogService tbBusinessLogService;
    @Autowired
    private TbBizPlaceMemberCardMapper tbBizPlaceMemberCardMapper;
    @Autowired
    private TbBizPlacePrivateOrderMapper tbBizPlacePrivateOrderMapper;
    @Autowired
    private TbPlaceTicketStatisticsMapper tbPlaceTicketStatisticsMapper;

    @Autowired
    private ApiPlaceTicketService apiPlaceTicketService;

    @Autowired
    private CouponService couponService;
    @Autowired
    private PlaceMemberWrapper placeMemberWrapper;

    @Autowired
    private TbBizPlaceMemberCardTypeMapper tbBizPlaceMemberCardTypeMapper;

    @Autowired
    private TbBizPlaceUnitCombineMapper pucMapper;

    @Autowired
    private TbBizPlaceUnitSalePlanMapper puspMapper;

    @Autowired
    PlaceOrderAdminCallbackService placeOrderAdminCallbackService;


    @Autowired
    PlaceGoodsService placeGoodsService;

    @Autowired
    PlaceOrderService placeOrderService;

    @Autowired
    PlaceInnerService placeInnerService;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    PlaceOrderUtilService placeOrderUtilService;
    @Autowired
    FinanceCommonManagerMapper commonManagerMapper;

    @Autowired
    CagetoryMapper cagetoryMapper;

    @Autowired
    TbPlaceTicketSalePlanMapper tbPlaceTicketSalePlanMapper;

    @Autowired
    FinanceCommonManagerMapper financeCommonManagerMapper;

    @Autowired
    TbBizPlaceOrderHistoryMapper tbBizPlaceOrderHistoryMapper;

    @Autowired
    ApiPlaceOrderService apiPlaceOrderService;

    @Autowired
    PlaceOrderAdminMapper placeOrderAdminMapper;

    @Autowired
    DictMapper dictMapper;



   

   

   
    private List<TbBizPlaceOrder>  selectPlaceOrderByOrderId(String placeOrderId){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbPlaceOrder = tbBizPlaceOrderExample.createCriteria();
        tbPlaceOrder.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        return tbBizPlaceOrders;
    }
  
    /**
     * 获取redis订单缓存队列名称，每个jvm进程消费自己的队列数据，避免队列资源消费出现锁冲突
     * @return
     */
    public static String getOrderCacheQueueName(){
        //TODO  只有请求才能获取ip和端口号，后台任务获取不了，需要改进
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        return PlaceConstants.PLACE_ORDER_CACHE_QUEUE_PREFIX + httpServletRequest.getLocalAddr() + "_" +httpServletRequest.getLocalPort();
    }


    private APIResponse payUserVerification(ReqPlaceOrderInfo reqPlaceOrderInfo){
        //获取用户信息
        if(reqPlaceOrderInfo.getUid() != null && reqPlaceOrderInfo.getUserInfo() == null){
            APIResponse<RespUserInfoBase> result = userServiceFacade.queryUserInfo(reqPlaceOrderInfo.getUid());
            if(!result.isRet()){
                return APIResponse.returnFail("不存在该用户！");
            }
            RespPlaceUserInfo respPlaceUserInfo = new RespPlaceUserInfo();
            try {
                BeanUtils.copyProperties(result.getData(), respPlaceUserInfo);
            }
            catch (Exception e){
                e.printStackTrace();
                return APIResponse.returnFail("服务器异常！");
            }
            reqPlaceOrderInfo.setUserInfo(respPlaceUserInfo);
        }
        return null;
    }


    /**
     *根据用户一天取消订单数、退订单数等验证用户是否可以下单
     * @param reqPlaceOrderInfo
     * @return
     */

    private APIResponse orderVerification(ReqPlaceOrderInfo reqPlaceOrderInfo){
        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqPlaceOrderInfo.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList =  tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        Map<String,String> placeOrderRuleMap = baseService.getPlaceOrderRule();
        int PLACE_PLAN_MAX_CLOSE = 0;//场馆一天最大取消订场次数
        int PLACE_ALL_ORDER_MAX_TIME = 0;//用户一天可预定最大的时段总数
        int PLACE_PLAN_MAX_PAYING = 0; //用户场地预定的最大未支付订单条数

        PLACE_PLAN_MAX_CLOSE = Integer.parseInt(placeOrderRuleMap.get("MAX_CANCEL_ORDRE_NUM"));//场馆一天最大取消订场次数
        PLACE_PLAN_MAX_PAYING = Integer.parseInt(placeOrderRuleMap.get("MAX_NON_PAYMENT_ORDER_NUM"));//用户场地预定的最大未支付订单条数
        if(CollectionUtils.isEmpty(tbBizPlaceRuleList)){
            PLACE_ALL_ORDER_MAX_TIME = PlaceConstants.PLACE_ALL_ORDER_MAX_TIME;
            logger.info("下单验证规则从默认配置中获取，placeId={}",reqPlaceOrderInfo.getPlaceId());
        }
        else {
            TbBizPlaceRule tbBizPlaceRule = tbBizPlaceRuleList.get(0);
            PLACE_ALL_ORDER_MAX_TIME = tbBizPlaceRule.getAllOrderMaxTime();//用户一天可预定最大的时段总数
        }

        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andUidEqualTo(reqPlaceOrderInfo.getUid());
        tbBizPlaceOrderCriteria.andOrderStatusChangeDateEqualTo(new Date());
        List<Byte> values = new ArrayList<>();
        values.add(PlaceConstants.ORDER_CLOSE_STATUS);
        values.add(PlaceConstants.ORDER_PREPAY_STATUS);
        tbBizPlaceOrderCriteria.andOrderStatusIn(values);

        int PLACE_PLAN_CLOSE_COUNT = 0;
        int PLACE_PLAN_PAYING_COUNT = 0;


        List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        if(CollectionUtils.isNotEmpty(placeOrderList)){
            for (TbBizPlaceOrder tbBizPlaceOrder : placeOrderList) {
                if(PlaceConstants.ORDER_PREPAY_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
                    PLACE_PLAN_PAYING_COUNT++;
                }
                if(PlaceConstants.ORDER_CLOSE_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
                    PLACE_PLAN_CLOSE_COUNT++;
                }
            }

            //判断用户是否已经取消两次订单
            if (PLACE_PLAN_CLOSE_COUNT >= PLACE_PLAN_MAX_CLOSE) {
                return APIResponse.returnFail("您一天之内已经取消订单"+PLACE_PLAN_MAX_CLOSE+"次，不能再下单，请明天再进行预定！");
            }
            //判断用户是否有两条未完成的订单，如果存在，提示用户支付
            if (PLACE_PLAN_PAYING_COUNT >= PLACE_PLAN_MAX_PAYING) {
                return APIResponse.returnFail("您有" + PLACE_PLAN_MAX_PAYING + "条未完成的订单，请先完成付款！");
            }

        }

        //获取订单总的销售计划小时
        Integer ORDER_SALE_PLAN_ALL_HOURS = tbBizPlaceOrderManagerMapper.countSalePlanHours(reqPlaceOrderInfo);

        Map<String,Object> map = new HashMap<>();
        map.put("date",DateUtils.transferDateToString(new Date()));
        map.put("uid",reqPlaceOrderInfo.getUid());
        map.put("placeId",reqPlaceOrderInfo.getPlaceId());

        //获取已经购买的销售计划小时数（统计用户当天下单的总的销售计划小时数，订单状态为未付款、已付款、已完成）
        int USER_ALL_ORDER_MAX_TIME = tbBizPlaceOrderManagerMapper.countUserPayOrderAllTimeByDay(map);
        if( (USER_ALL_ORDER_MAX_TIME + ORDER_SALE_PLAN_ALL_HOURS > PLACE_ALL_ORDER_MAX_TIME) && (PLACE_ALL_ORDER_MAX_TIME > USER_ALL_ORDER_MAX_TIME)){
            Integer REMAINED_HOURS = PLACE_ALL_ORDER_MAX_TIME - USER_ALL_ORDER_MAX_TIME;
            return APIResponse.returnFail("该场馆您只能再预定" + REMAINED_HOURS + "小时！" );
        }
        if(USER_ALL_ORDER_MAX_TIME + ORDER_SALE_PLAN_ALL_HOURS > PLACE_ALL_ORDER_MAX_TIME){
            return APIResponse.returnFail("您已经超过一天可预定最大的时段总数：" +PLACE_ALL_ORDER_MAX_TIME + "小时！" );
        }

        return null;
    }

   

    private APIResponse<RespPreOrder> noticeOrderSystem(ReqPlaceOrderInfo reqPlaceOrderInfo,TbBizPlace tbBizPlace,List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList,boolean isVip){
        logger.info("noticeOrderSystem(ReqPlaceOrderInfo reqPlaceOrderInfo--->"+JSON.toJSONString(reqPlaceOrderInfo));
        com.quanyan.api.APIRequest<ReqOrderSave> reqOrderSaveAPIRequest = new com.quanyan.api.APIRequest<>();
        ReqOrderSave reqOrderSave = new ReqOrderSave();

        reqOrderSave.setSourceBusinessId(Constants.PLACE_BOOKING_CODE);
        reqOrderSave.setSourceSystemId(Constants.PLACE_SYSTEM_CODE);
        reqOrderSave.setPlatformType(reqPlaceOrderInfo.getPlatformType());//设置平台类型
        reqOrderSave.setContactMobile(reqPlaceOrderInfo.getUserInfo().getMobile());
        reqOrderSave.setContactName(reqPlaceOrderInfo.getUserInfo().getNickName());
        reqOrderSave.setExtraParam("");
        if(reqPlaceOrderInfo.getCityId() != null && reqPlaceOrderInfo.getCityId().equals(3)){
            reqOrderSave.setMchId(3); //此处为城市ID，必填
        }else {
            reqOrderSave.setMchId(2); //此处为城市ID，必填
        }
        //微信小程序
        Integer mchId = reqPlaceOrderInfo.getMchId();
        if (null != mchId){
            reqOrderSave.setMchId(mchId);
        }

        //如果回调类型为0，则订单系统使用http方式进行回调；如果回调类型为1，使用mq进行处理
        if(reqPlaceOrderInfo.getCallbackType().equals(Constants.IS_NO)){
            reqOrderSave.setNotifyURL(payUrl);
            reqOrderSave.setCloseNotifyURL(closeOrderUrl);
            reqOrderSave.setRefundNotifyURL(refundUrl);
            reqOrderSave.setExceptionRefundNotify(exceptionRefundUrl);
            logger.info("订单号：{}，支付使用http回调处理。",reqPlaceOrderInfo.getOrderNo());
        }
        else {
            logger.info("订单号：{}，支付使用mq消息处理。",reqPlaceOrderInfo.getOrderNo());
        }
        //
        if(isVip){
            List<ReqPayInfo> requestPayInfo = reqPlaceOrderInfo.getPayInfos();
            if (requestPayInfo.size() == 1 && requestPayInfo.get(0).getPayId().equals(PlaceConstants.PAY_WAY_FOR_CARD)){
                reqOrderSave.setOrderAmount(reqPlaceOrderInfo.getPayInfos().get(0).getAmount());
            }else{
                for (ReqPayInfo reqPayInfo : requestPayInfo) {
                    if (reqPayInfo.getPayId().equals(PlaceConstants.PAY_WAY_FOR_COUPON) || reqPayInfo.getPayId().equals(PlaceConstants.PAY_WAY_FOR_CARD)){
                        reqOrderSave.setOrderAmount(reqPlaceOrderInfo.getOrderAmount());
                        break;
                    }
                }
            }
        }else {
            reqOrderSave.setOrderAmount(reqPlaceOrderInfo.getOrderAmount());
        }

        reqOrderSave.setOrderDescribe("预定" + tbBizPlace.getName());
        reqOrderSave.setOrderURL(tbBizPlace.getBizPlaceUrl());
        reqOrderSave.setOutTradeNo(reqPlaceOrderInfo.getOrderNo());
        reqOrderSave.setPayNote("");
        reqOrderSave.setUserClientIp("");
        reqOrderSave.setPayTimeOut(PlaceConstants.PAYTIMEOUT);
        reqOrderSave.setUid(reqPlaceOrderInfo.getUserInfo().getUid());
        reqOrderSave.setShowURL(reqPlaceOrderInfo.getSubjectURL());
        reqOrderSave.setEggInfo(tbBizPlace.getName() + "订场费");
        reqOrderSave.setEggReceiver("百灵鸟");
        reqOrderSave.setVer(reqPlaceOrderInfo.getVer());//设置版本号
        if (!org.springframework.util.StringUtils.isEmpty(reqPlaceOrderInfo.getReturnUrlForH5())){
            reqOrderSave.setReturnUrlForH5(reqPlaceOrderInfo.getReturnUrlForH5());
        }
        if (!org.springframework.util.StringUtils.isEmpty(reqPlaceOrderInfo.getShowURLForH5())){
            reqOrderSave.setShowURLForH5(reqPlaceOrderInfo.getShowURLForH5());
        }
        if(reqPlaceOrderInfo.getOpenId() != null){
            reqOrderSave.setBuyerAccount(reqPlaceOrderInfo.getOpenId());
        }
        else {
            reqOrderSave.setBuyerAccount("");
        }

        reqOrderSave.setService(PlaceConstants.SERVICE_CODE);


        List<ReqProductDetail> reqProductDetailList = new ArrayList<>();
        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            ReqProductDetail reqProductDetail = new ReqProductDetail();
            reqProductDetail.setShowURL(tbBizPlace.getBizPlaceUrl());
            if(isVip){
                reqProductDetail.setPrice(tbBizPlaceUnitSalePlan.getMemberPrice());
            }
            else {
                reqProductDetail.setPrice(tbBizPlaceUnitSalePlan.getPrice());
            }
            reqProductDetail.setProductDesc(tbBizPlace.getName());
            reqProductDetail.setProductId(tbBizPlaceUnitSalePlan.getSaleId());
            reqProductDetail.setProductName(DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()) + "-" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime())+"时段");
            reqProductDetail.setProductURL(tbBizPlace.getBizPlaceUrl());
            reqProductDetail.setQuantity(1);
            reqProductDetailList.add(reqProductDetail);
        }

        reqOrderSave.setProductDetailList(reqProductDetailList);
        reqOrderSave.setPayInfos(reqPlaceOrderInfo.getPayInfos());
        reqOrderSaveAPIRequest.setData(reqOrderSave);
        logger.info("orderPayService.submitOrder--->"+JSON.toJSONString(reqOrderSaveAPIRequest));
        APIResponse<RespPreOrder> respPreOrderAPIResponse = orderPayService.submitOrder(reqOrderSaveAPIRequest);
        return respPreOrderAPIResponse;
    }


    /**
     * 检验销售计划有没有重叠
     * @param tbBizPlaceUnitSalePlanList
     * @return
     */
    public APIResponse salePlansVerification(List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList) {
        Set<String> uniqSaleIds = new HashSet<>();

        for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
            List<String> saleIds = new ArrayList<>();

            if (tbBizPlaceUnitSalePlan == null) {
                continue;
            }

            String saleId = tbBizPlaceUnitSalePlan.getSaleId();
            if (saleId != null) {
                saleIds.add(saleId);
            }

            if (UNIT_TYPE_COMBINE.equals(tbBizPlaceUnitSalePlan.getUnitType())) {
                String subSaleplans = tbBizPlaceUnitSalePlan.getSubSaleplans();
                List<String> subSaleplanIds = new ArrayList<>();
                if (subSaleplans != null) {
                    subSaleplanIds = Arrays.asList(subSaleplans.split("[|]"));
                }

                if (subSaleplanIds != null && subSaleplanIds.size() > 0) {
                    saleIds.addAll(subSaleplanIds);
                }
            }

            for (String curSaleId : saleIds) {
                if (uniqSaleIds.contains(curSaleId)) {
                    return APIResponse.returnFail("销售计划" + saleId + "有重叠！" );
                } else {
                    uniqSaleIds.add(curSaleId);
                }
            }
        }

        return null;
    }

    @Override
    public APIResponse<?> orderOperate(ReqOrderOperate reqOrderOperate) {
        if(PlaceConstants.ORDER_CANCEL_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCancelOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_COMPLETE_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCompletePayOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_UNSUBSCRIBE_OPERATE.equals(reqOrderOperate.getOperateType())){//申请退款
            return orderUnsubscribeOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_COMPLETE_UNSUBSCRIBE_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCompleteUnsubscribeOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_CANCEL_TO_UNSUBSCRIBE_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderCancleToUnsubscribeOperate(reqOrderOperate);
        }
        else if (PlaceConstants.ORDER_PAY_CONFIRM_OPERATE.equals(reqOrderOperate.getOperateType())){
            return orderPayConfirmOperate(reqOrderOperate);
        }
        return APIResponse.returnFail("订单处理类型参数输入错误！");
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCancleToUnsubscribeOperate(ReqOrderOperate reqOrderOperate) {
        //需要进行权限控制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());

        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());
        if(tbBizPlaceOrder == null){
            String childrenOrderNo = reqOrderOperate.getRefundOrderNo();//退款订单为子订单
            TbBizPlaceOrder childrenOrder = getBizPlaceOrderForBookAll(childrenOrderNo);
            if (childrenOrder == null){
                return APIResponse.returnFail("没有该条订单信息！");
            }
            //包场退款异常回调
            return placeOrderAdminCallbackService.bookAllOrderCancleToUnsubscribeOperate(reqOrderOperate,childrenOrder);
        }
        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCancleToUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
            return placeOrderAdminCallbackService.billingOrderCancleToUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderAdminCallbackService.goodsOrderCancleToUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderAdminCallbackService.shoppingCartOrderCancleToUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if (CollectionUtils.isNotEmpty(placeOrderSalePlanList)) {
            if (PlaceConstants.ORDER_CLOSE_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                /*//设置订单状态和支付状态为已经退款状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
                tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                TbBizPlaceOrder record = new TbBizPlaceOrder();
                record.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
                record.setPayStatus(PlaceConstants.REFUNDING_STATUS);
                Date date = new Date();
                record.setOrderStatusChangeDate(date);
                record.setRefundTime(date);
                record.setEndTime(date);
                record.setDebit(new BigDecimal(0));
                record.setCredit(placeOrderSalePlanList.get(0).getDebit());
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

                //更改订单支付明细的状态为退款状态
                TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
                tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,tbBizPlacePayItemExample);*/

                //设置退款中状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
                tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                TbBizPlaceOrder tbBizPlaceRecord = new TbBizPlaceOrder();
                tbBizPlaceRecord.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
                tbBizPlaceRecord.setOrderStatusChangeDate(new Date());

                tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceRecord, tbBizPlaceOrderExample1);

                List<Integer> values = new ArrayList<>();
                values.add(PlaceConstants.PAY_WAY_ALIPAY);
                values.add(PlaceConstants.PAY_WAY_WEICHAT);
                values.add(PlaceConstants.PAY_WAY_WEICHATH5);
                values.add(PlaceConstants.PAY_WAY_UNION_PAY);
                values.add(PlaceConstants.PAY_WAY_APPLE_PAY);
                values.add(PlaceConstants.PAY_WAY_FOR_WEB_ALIPAY);
                values.add(PlaceConstants.PAY_WAY_FOR_WEIXIN_APPLET);

                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemCriteria.andPayTypeIn(values);
                List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                    APIResponse.returnFail("没有该条订单信息！");
                }

                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter != null && parameter.getParameterValue() != null) {
                    if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }


                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());

                //加入消息推送，提示订场成功
                PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(3);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setPayType(tbBizPlacePayItemList.get(0).getPayType());
                boolean result = pushMessageOperate(placeMessage);
                //异常时加入消息队列进行异步消息推送处理
                if(!result){
                    mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
                }

                //TODO 发送短息

                return APIResponse.returnSuccess("订单退款受理成功！");

            }
            else if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                return APIResponse.returnFail("订单退款已经受理！");
            }
            else {
                logger.warn("订单退款异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单退款异常！");
            }
        }
        return APIResponse.returnFail("不存在该退款订单！");
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderPayConfirmOperate(ReqOrderOperate reqOrderOperate) {
        //需要进行权限限制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");

        }

        String orderNo = reqOrderOperate.getOrderNo();
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(orderNo);
        if (tbBizPlaceOrder != null){
            if (!tbBizPlaceOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlaceOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
                return APIResponse.returnFail("订单不是未支付状态！");
            }
        }
        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = null;
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = null;
        if (tbBizPlaceOrder==null){
            tbBizPlacePrivateOrder = getBizPlacePrivateOrder(orderNo);
            if (tbBizPlacePrivateOrder!=null){
                if (!tbBizPlacePrivateOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlacePrivateOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
                    return APIResponse.returnFail("订单不是未支付状态！");
                }
                //包场支付回调
                return placeOrderAdminCallbackService.bookAllOrderCompletePayOperate(reqOrderOperate);
            }
            tbBizPlaceMemberOpHistory = getBizPlaceMemberHistory(orderNo);
            if (tbBizPlaceMemberOpHistory!=null){
                if (tbBizPlaceMemberOpHistory.getState().byteValue() != PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO && tbBizPlaceMemberOpHistory.getNo() != null){
                    return APIResponse.returnFail("开卡充值记录不是未支付状态！");
                }
                //商家端会员卡扫码支付充值回调
                if(MerchantClientPayType.getMatchScanPayType().containsKey(tbBizPlaceMemberOpHistory.getPayType().toString())){//update by tim
                    return placeOrderAdminCallbackService.cardOrderCompletePayOperate(reqOrderOperate);
                }

            }
            return APIResponse.returnFail("没有该条订单信息！");
        }
        //商家端门票支付成功回调
        if (tbBizPlaceOrder.getSourceType().equals(PlaceConstants.SOURCE_TYPE_SCENEPAY)
                &&tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderAdminCallbackService.ticketOrderCompletePayOperate(reqOrderOperate);
        }
        //商家端扫码开单包场回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                ||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
            return placeOrderAdminCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderAdminCallbackService.goodsOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderAdminCallbackService.shoppingCartOrderCompletePayOperate(reqOrderOperate);
        }

        return APIResponse.returnFail("没有该条订单信息！");

    }
    
    /**
     * 订单取消处理
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCancelOperate(ReqOrderOperate reqOrderOperate){
        //订单取消验证
        if(PlaceConstants.YES.equals(reqOrderOperate.getIsCallBackOrder())){
            HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
            Integer userId = (Integer)httpServletRequest.getAttribute("uid");
            if(userId != null && userId != 0 ){
                reqOrderOperate.setUid(userId);
            }
        }

        APIResponse apiResponse = orderCancelOperateVerification(reqOrderOperate);
        if(apiResponse != null){
            return apiResponse;
        }

        String orderNo = reqOrderOperate.getOrderNo();
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());

        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = null;
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = null;
        if (tbBizPlaceOrder==null){
            tbBizPlacePrivateOrder = getBizPlacePrivateOrder(orderNo);
            if (tbBizPlacePrivateOrder!=null){
                //包场取消回调
                return placeOrderAdminCallbackService.bookAllOrderCancelOperate(reqOrderOperate);
            }
            tbBizPlaceMemberOpHistory = getBizPlaceMemberHistory(orderNo);
            if (tbBizPlaceMemberOpHistory!=null){
                //会员开卡和充值  防止订单系统反复回调return success
                return APIResponse.returnSuccess("会员卡业务成功！");
            }
            return APIResponse.returnFail("没有该条订单信息！");
        }

        //场馆订单如果为门票，走门票逻辑
        if(tbBizPlaceOrder.getUseType() != null && tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return apiPlaceTicketService.orderCancelOperate(reqOrderOperate);
        }
        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCancelOperate(reqOrderOperate);
        }*/
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
            return placeOrderAdminCallbackService.billingOrderCancelOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderAdminCallbackService.goodsOrderCancelOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderAdminCallbackService.shoppingCartOrderCancelOperate(reqOrderOperate);
        }

        //判断订单状态为付款中状态，销售计划状态为正在预定状态
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)){
            if(PlaceConstants.ORDER_PREPAY_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){

                //通知订单系统，订单已经被取消
                if(PlaceConstants.YES.equals(reqOrderOperate.getIsCallBackOrder())){
                    logger.info("通知订单系统关闭订单，订单号：{}",reqOrderOperate.getOrderNo());
                    APIRequest<ReqOrderCancel> orderCancelAPIRequest = new APIRequest<>();
                    ReqOrderCancel reqOrderCancel = new ReqOrderCancel();
                    reqOrderCancel.setOrderNo(placeOrderSalePlanList.get(0).getOrderNo());
                    reqOrderCancel.setOutTradeNo(placeOrderSalePlanList.get(0).getPlaceOrderId());
                    reqOrderCancel.setUid(reqOrderOperate.getUid());
                    reqOrderCancel.setSourceBusinessId(PlaceConstants.PLACE_BUSINESS_CODE);
                    reqOrderCancel.setSourceSystemId(Constants.PLACE_SYSTEM);
                    reqOrderCancel.setCancelReason(reqOrderOperate.getReason());
                    reqOrderCancel.setVer(reqOrderOperate.getVer());
                    orderCancelAPIRequest.setData(reqOrderCancel);

                    APIResponse<BaseEnum> apiResponseOrderCancel = this.orderPayService.orderCancel(orderCancelAPIRequest);
                    if(apiResponseOrderCancel == null || !apiResponseOrderCancel.isRet()){
                        return APIResponse.returnFail("订单取消失败，请重试！");
                    }
                }

                //设置订单状态为已经关闭状态，释放库存
                ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
                reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                reqPlaceOrderListVo.setUid(null);//清理uid
                reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
                List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    UnitSalePlan unitSalePlan = new UnitSalePlan();
                    unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
                    unitSalePlanIdList.add(unitSalePlan);
                }
                reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
                placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);

                //设置订单状态为关闭状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
                tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                TbBizPlaceOrder record = new TbBizPlaceOrder();
                record.setOrderStatus(PlaceConstants.ORDER_CLOSE_STATUS);
                record.setOrderStatusChangeDate(new Date());
                record.setEndTime(new Date());
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

                //更改订单支付明细的状态为取消状态
                TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
                tbBizPlacePayItem.setAmountType(PlaceConstants.CANCEL_TYPE);
                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem,tbBizPlacePayItemExample);

                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter != null && parameter.getParameterValue() != null) {
                    if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }

                return APIResponse.returnSuccess("订单取消成功！");
            }
            else if(PlaceConstants.ORDER_CLOSE_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){
                return APIResponse.returnSuccess("订单取消已经受理！");
            }
            else {
                logger.warn("订单取消异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单取消异常！");
            }
        }
        return APIResponse.returnFail("没有该条订单信息！");
    }

    /**
     * 用户取消订单验证
     * @param reqOrderOperate
     * @return
     */
    private APIResponse orderCancelOperateVerification(ReqOrderOperate reqOrderOperate){
        if(PlaceConstants.ORDER_OPERATE_APPUSER.equals(reqOrderOperate.getUserType())){
            Map<String,String> placeOrderRuleMap = baseService.getPlaceOrderRule();
            int PLACE_PLAN_MAX_CLOSE = 0;
            PLACE_PLAN_MAX_CLOSE = Integer.parseInt(placeOrderRuleMap.get("MAX_CANCEL_ORDRE_NUM"));//场馆一天最大取消订场次数
            TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
            tbBizPlaceOrderCriteria.andUidEqualTo(reqOrderOperate.getUid());
            tbBizPlaceOrderCriteria.andOrderStatusChangeDateEqualTo(new Date());
            tbBizPlaceOrderCriteria.andOrderStatusEqualTo(PlaceConstants.ORDER_CLOSE_STATUS);
            List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
            if(CollectionUtils.isNotEmpty(placeOrderList)){
                if (placeOrderList.size() >= PLACE_PLAN_MAX_CLOSE) {
                    return APIResponse.returnFail("您一天之内已经取消订单" + PLACE_PLAN_MAX_CLOSE + "次，不能再取消！");
                }
            }
        }
        return null;
    }

    /**
     * 如果支付系统完成支付，进行订单回调处理
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCompletePayOperate(ReqOrderOperate reqOrderOperate){
        //需要进行权限限制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");

        }

        String orderNo = reqOrderOperate.getOrderNo();
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(orderNo);

        if (tbBizPlaceOrder!=null){
            if (!tbBizPlaceOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlaceOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
                return APIResponse.returnFail("订单不是未支付状态！");
            }
        }


        TbBizPlacePrivateOrder tbBizPlacePrivateOrder = null;
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = null;
        if (tbBizPlaceOrder==null){
            tbBizPlacePrivateOrder = getBizPlacePrivateOrder(orderNo);
            if (tbBizPlacePrivateOrder!=null){
                if (!tbBizPlacePrivateOrder.getOrderStatus().equals(PlaceConstants.ORDER_PREPAY_STATUS) && !tbBizPlacePrivateOrder.getPayStatus().equals(PlaceConstants.NOT_PAY_STATUS)){
                    return APIResponse.returnFail("订单不是未支付状态！");
                }
                //包场支付回调
                return placeOrderAdminCallbackService.bookAllOrderCompletePayOperate(reqOrderOperate);
            }
            tbBizPlaceMemberOpHistory = getBizPlaceMemberHistory(orderNo);
            if (tbBizPlaceMemberOpHistory!=null){
                if (!tbBizPlaceMemberOpHistory.getState().equals(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO)){
                    return APIResponse.returnFail("开卡充值记录不是未支付状态！");
                }
                //商家端会员卡扫码支付充值回调
                if (tbBizPlaceMemberOpHistory.getPayType().toString().equals(PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN)
                        || tbBizPlaceMemberOpHistory.getPayType().toString().equals( PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN)||tbBizPlaceMemberOpHistory.getPayType().toString().equals( PlaceConstants.PLACE_ADMIN_PAY_WAYS_PO_UNIONPAY)){//add by tim,增加银联pos支付
                    return placeOrderAdminCallbackService.cardOrderCompletePayOperate(reqOrderOperate);
                }
                //app会员卡开卡充值回调
                if (tbBizPlaceMemberOpHistory.getPayType() == PlaceConstants.PAY_WAY_ALIPAY
                        || tbBizPlaceMemberOpHistory.getPayType() == PlaceConstants.PAY_WAY_WEICHAT){
                    return placeOrderAdminCallbackService.appCardChargeOrderCompletePayOperate(reqOrderOperate, tbBizPlaceMemberOpHistory);
                }
            }
            return APIResponse.returnFail("没有该条订单信息！");
        }
        //商家端门票支付成功回调
        if (tbBizPlaceOrder.getSourceType().equals(PlaceConstants.SOURCE_TYPE_SCENEPAY)
                &&tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderAdminCallbackService.ticketOrderCompletePayOperate(reqOrderOperate);
        }
        //门票支付回调
        if(tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            reqOrderOperate.setPlaceId(tbBizPlaceOrder.getPlaceId());
            return orderCompleteTicketOperate(reqOrderOperate);
        }

       /* if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCompletePayOperate(reqOrderOperate, tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCompletePayOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单包场回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)
                ||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)){
            return placeOrderAdminCallbackService.billingOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderAdminCallbackService.goodsOrderCompletePayOperate(reqOrderOperate);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderAdminCallbackService.shoppingCartOrderCompletePayOperate(reqOrderOperate);
        }


        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());
        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)) {

            if (PlaceConstants.ORDER_PREPAY_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                //将销售计划表状态设置为已经预定状态
                ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
                reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_ORDER_STATUS);
                reqPlaceOrderListVo.setUid(reqOrderOperate.getUid());
                reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
                List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    UnitSalePlan unitSalePlan = new UnitSalePlan();
                    unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
                    unitSalePlanIdList.add(unitSalePlan);
                }
                reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
                placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);

                //设置订单状态为已经付款状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
                tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                TbBizPlaceOrder record = new TbBizPlaceOrder();
                record.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
                record.setPayStatus(PlaceConstants.PAY_STATUS);
                Date date = new Date();
                record.setOrderStatusChangeDate(date);
                record.setPaymentTime(reqOrderOperate.getPayTime());
                record.setEndTime(date);
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample1);

                //馆报名人数加一
                Map<String,Object> map = new HashMap<>();
                map.put("placeId", placeOrderSalePlanList.get(0).getPlaceId());
                map.put("addSignupCount", 1);
                placeMapper.updateCount(map);

                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());

                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                List<Integer>  payTypeList = PlaceOrderUtil.getPayType();
                tbBizPlacePayItemCriteria.andPayTypeIn(payTypeList);
                List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                    APIResponse.returnFail("没有该条订单信息！");
                }

                //加入消息推送，提示订场成功
                PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(1);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setPayType(tbBizPlacePayItemList.get(0).getPayType());
                Cagetory cagetory =cagetoryMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getCategoryId());
                placeMessage.setCategoryValue(cagetory.getName());

                boolean result = pushMessageOperate(placeMessage);
                //加入消息队列进行异步消息推送处理，场馆系统自己作为生产者也作为消费者。
                if(!result){
                    mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
                }

                //发送短信
                smsSendOperate(placeOrderSalePlanList, null, reqOrderOperate.getUid(), tbBizPlace);
               // insertOrderRecordHistory(reqOrderOperate);
                /**支付系统完成**/
                orderCallBackHistory(reqOrderOperate);
                /*//发送mq消息给运动场业务
                PlaceOrderVo placeOrderVo = new PlaceOrderVo();
                placeOrderVo.setUid(reqOrderOperate.getUid());
                placeOrderVo.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeOrderVo.setCategoryId(placeOrderSalePlanList.get(0).getCategoryId());
                placeOrderVo.setPlaceOrderId(reqOrderOperate.getOrderNo());
                List<PlaceOrderProduct> placeOrderProductList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    PlaceOrderProduct placeOrderProduct = new PlaceOrderProduct();
                    placeOrderProduct.setEndTime(placeOrderSalePlan.getEndTime());
                    placeOrderProduct.setStartTime(placeOrderSalePlan.getStartTime());
                    placeOrderProduct.setPlaceUnitId(placeOrderSalePlan.getPlaceUnitId());
                    placeOrderProduct.setPlaceUnitName(placeOrderSalePlan.getPlaceUnitName());
                    placeOrderProductList.add(placeOrderProduct);
                }
                placeOrderVo.setType(1);
                placeOrderVo.setPlaceOrderProductList(placeOrderProductList);
                mqPlaceProductWrapper.sendOrderInfoToStadium(placeOrderVo);*/

                /*try {
                    this.searchService.addPlaceIndex(tbBizPlace, null);
                } catch (Exception e) {
                    logger.error("增加索引失败，加入消息队列进行处理!");
                    //加入消息队列进行异步索引添加处理
                    TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
                    tbBizPlaceVo.setTbBizPlace(tbBizPlace);
                    mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
                }*/

                return APIResponse.returnSuccess("订单支付完成！");
            }
            else if(PlaceConstants.ORDER_PAYED_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                return APIResponse.returnSuccess("订单已经支付成功！");
            }
            else{
                logger.warn("订单完成支付异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单完成支付异常！");
            }
        }

        return APIResponse.returnFail("没有该条订单信息！");
    }
    /**
     * 订场成功发送短信通知用户
     * @param placeOrderSalePlanList
     * @param uid
     * @param tbBizPlace
     * @return
     */
    @Async
    private boolean smsSendOperate(List<PlaceOrderSalePlan> placeOrderSalePlanList,List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList,Integer uid, TbBizPlace tbBizPlace){
        if(CollectionUtils.isEmpty(placeOrderSalePlanList) && CollectionUtils.isEmpty(tbBizPlaceUnitSalePlanList)){
            return false;
        }
        List<String> mobiles=new ArrayList<>();
        List<String> params=new ArrayList<>();
        String phone="";
        String [] args = new String[3];
        args[0] = "";
        args[1] = "";
        args[2] = "";
        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            phone=placeAttach.getBookingConsultPhone();
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            phone=parameterVo!=null?parameterVo.getParameterValue():"";
        }

        if(CollectionUtils.isNotEmpty(tbBizPlaceUnitSalePlanList)){
            Comparator<TbBizPlaceUnitSalePlan> comparator = new Comparator<TbBizPlaceUnitSalePlan>() {
                @Override
                public int compare(TbBizPlaceUnitSalePlan o1, TbBizPlaceUnitSalePlan o2) {
                    return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

                }
            };
            Collections.sort(tbBizPlaceUnitSalePlanList, comparator);
            String salePlanDate = DateUtils.transferDateToString(tbBizPlaceUnitSalePlanList.get(0).getDate());
            String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
            args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + tbBizPlaceUnitSalePlanList.get(0).getCategoryId().toString());
            for (TbBizPlaceUnitSalePlan tbBizPlaceUnitSalePlan : tbBizPlaceUnitSalePlanList) {
                args[1] +=tbBizPlaceUnitSalePlan.getPlaceUnitName()+" "+ " " + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getStartTime()) + "-" + DateTimeUtils.timeToStr(tbBizPlaceUnitSalePlan.getEndTime()) + "、";
            }
            args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";
            args[2] = phone;
        }
        else if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)){
            Comparator<PlaceOrderSalePlan> comparator = new Comparator<PlaceOrderSalePlan>() {
                @Override
                public int compare(PlaceOrderSalePlan o1, PlaceOrderSalePlan o2) {
                    return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

                }
            };
            Collections.sort(placeOrderSalePlanList, comparator);

            String salePlanDateNew = DateUtils.tranferStringToZHCN(placeOrderSalePlanList.get(0).getDate());
            args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + placeOrderSalePlanList.get(0).getCategoryId().toString());
            for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                String startTime = placeOrderSalePlan.getStartTime();
                String endTime = placeOrderSalePlan.getEndTime();
                args[1] +=placeOrderSalePlan.getPlaceUnitName()+" "+ " " +  startTime.substring(0,startTime.length()-3) + "-" + endTime.substring(0,endTime.length()-3) + "、";
            }
            args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";
            args[2] = phone;
        }

        APIResponse<RespUserInfoBase> userMsg = userServiceFacade.queryUserInfo(uid);
        if(!userMsg.isRet()){
            return false;
        }
        RespUserInfoBase respUserInfoBase = userMsg.getData();
        mobiles.add(respUserInfoBase.getMobile());
        params.addAll(Arrays.asList(args));
        try {
            //placeTicketService.asyncSendSms(respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_NOTICE,args,true);
            placeSmsService.sendSms(mobiles,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,params);
        } catch(Exception e){
            logger.info("短信发送失败-------->" + e.getMessage());
            return false;
        }

        //发送短信提醒给场馆人员
        TbBizPlaceNoticeMobile messageVo = placeMessageService.getMobileDataByPlaceId(tbBizPlace.getId());
        APIResponse<RespUserInfoBase>  userInfo=userServiceFacade.queryUserInfo(uid);
        String nickName=userInfo.getData()!=null ? userInfo.getData().getNickName():"";
        if (null != messageVo){
            APIResponse<RespUserInfoBase> resPvo = userServiceFacade.queryUserInfo(uid);
            List<String> mobileList=new ArrayList<>();
            List<String> paramList=new ArrayList<>();
            String[] messageArgs = new String[4];
            messageArgs[0] = nickName;
           // messageArgs[0] = resPvo != null ? resPvo.getData().getMobile() : "";
            messageArgs[1]=args[0];
            messageArgs[2]=args[1];
            messageArgs[3]=resPvo != null ? resPvo.getData().getMobile() : "";
            mobileList.add(messageVo.getMobile());
            paramList.addAll(Arrays.asList(messageArgs));
            try {
                if (!StringUtils.isEmpty(messageVo.getMobile())) {
                    placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_REMIND, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
                }
            } catch (java.lang.Exception e) {
                logger.info("短信发送失败-------->" + e.getMessage());
            }
        }
        return true;
    }

    /**
     * 门票支付完成回调操作
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse orderCompleteTicketOperate(ReqOrderOperate reqOrderOperate){
        logger.info("门票支付完成回调---->"+JSON.toJSONString(reqOrderOperate));
            //设置订单状态为已经付款状态
            TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
            tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

            TbBizPlaceOrder record = new TbBizPlaceOrder();
            record.setOrderStatus(PlaceConstants.ORDER_PAYED_STATUS);
            record.setPayStatus(PlaceConstants.PAY_STATUS);
            Date date = new Date();
            record.setOrderStatusChangeDate(date);
            record.setPaymentTime(reqOrderOperate.getPayTime());
            record.setEndTime(date);
            tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample1);

            //馆报名人数加一
            Map<String,Object> map = new HashMap<>();
            map.put("placeId", reqOrderOperate.getPlaceId());
            map.put("addSignupCount", 1);
            placeMapper.updateCount(map);

            TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(reqOrderOperate.getPlaceId());

            TbBizPlaceOrderItemExample tbBizPlaceOrderItemExample = new TbBizPlaceOrderItemExample();
            TbBizPlaceOrderItemExample.Criteria placeOrderItem = tbBizPlaceOrderItemExample.createCriteria();
            placeOrderItem.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
            List<TbBizPlaceOrderItem> tbBizPlaceOrderItems = tbBizPlaceOrderItemMapper.selectByExample(tbBizPlaceOrderItemExample);
            PlaceTicketPushOrderVo placeTicketPushOrderVo = new PlaceTicketPushOrderVo();

            if(CollectionUtils.isEmpty(tbBizPlaceOrderItems)){
                APIResponse.returnFail("没有该条订单信息！");
            }else{
                List<TicketPushOrderVo> lists = new ArrayList<>();
                for (TbBizPlaceOrderItem tbBizPlaceOrderItem : tbBizPlaceOrderItems) {
                    Integer ticketId = tbBizPlaceOrderItem.getUnitSalePlanId();
                    TbPlaceTicketSalePlan placeTicketSalePlan = tbPlaceTicketSalePlanMapper.selectByPrimaryKey(ticketId);
                    TicketPushOrderVo ticketPush = new TicketPushOrderVo();
                    ticketPush.setTicketName(placeTicketSalePlan.getTicketName());
                    ticketPush.setStartTime(placeTicketSalePlan.getStartTime());
                    ticketPush.setEndTime(placeTicketSalePlan.getEndTime());
                    lists.add(ticketPush);
                }
                placeTicketPushOrderVo.setTicketPushOrderVos(lists);
            }
            TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
            TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
            tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
            List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
            if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                APIResponse.returnFail("没有该条订单信息！");
            }



            TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbPlaceOrder = tbBizPlaceOrderExample.createCriteria();
            tbPlaceOrder.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
            List<TbBizPlaceOrder> tbBizPlaceOrders = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
            if(CollectionUtils.isEmpty(tbBizPlaceOrders)){
                APIResponse.returnFail("没有该条订单信息！");
            }

            /**设置服务开关
             * ServiceSwitch 0:不支持，1:支持
             * **/
            TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
            if (parameter != null && parameter.getParameterValue() != null) {
                if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                    OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                    orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                    APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                    if (callBackOrderStatus != null){
                        APIResponse.returnFail("更新订单状态异常");
                    }
                }
            }


            /**加入消息推送，购买门票成功**/
            PlaceMessage placeMessage = new PlaceMessage();
            placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
            placeMessage.setOrderType(4);
            List<Integer> uids = new ArrayList<>();
            uids.add(reqOrderOperate.getUid());
            placeMessage.setUids(uids);

            String salePlanDate =DateUtils.transferDateToString(tbBizPlaceOrderItems.get(0).getConsumeTime());
            String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);

            placeMessage.setDate(salePlanDateNew);
            placeMessage.setPlaceName(tbBizPlace.getName());
            placeMessage.setPlaceId(reqOrderOperate.getPlaceId());

            placeMessage.setPayType(tbBizPlacePayItemList.get(0).getPayType());
            Cagetory cagetory =cagetoryMapper.selectByPrimaryKey(tbBizPlaceOrders.get(0).getCategoryId());
            placeMessage.setCategoryValue(cagetory.getName());
            boolean result = pushMessageOperate(placeMessage);
            //加入消息队列进行异步消息推送处理，场馆系统自己作为生产者也作为消费者。
            if(!result){
                mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
            }
            //insertOrderRecordHistory(reqOrderOperate);
            placeTicketPushOrderVo.setDate(salePlanDateNew);
            placeTicketPushOrderVo.setCategoryId(tbBizPlaceOrders.get(0).getCategoryId());
            /**门票支付完成**/
            orderCallBackHistory(reqOrderOperate);

            //发送短信
            ticketSmsSendOperate(placeTicketPushOrderVo, reqOrderOperate.getUid(), tbBizPlace);

            return APIResponse.returnSuccess("订单支付完成！");


    }

    /**
     * 订单退款
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse orderUnsubscribeOperate(ReqOrderOperate reqOrderOperate){
        HttpServletRequest httpServletRequest = ServletUtils.getHttpServletRequest();
        Integer userId = (Integer)httpServletRequest.getAttribute("uid");
        if(userId != null && userId != 0 ){
            reqOrderOperate.setUid(userId);
        }
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());
        if (tbBizPlaceOrder==null){
            //包场退款中回调
            String childrenOrderNo = reqOrderOperate.getRefundOrderNo();//退款订单为子订单
            TbBizPlaceOrder childrenOrder = getBizPlaceOrderForBookAll(childrenOrderNo);
            if (childrenOrder == null){
                return APIResponse.returnFail("没有该条订单信息！");
            }
            return placeOrderAdminCallbackService.bookAllOrderUnsubscribeOperate(reqOrderOperate,childrenOrder);
        }
        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单与App回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)||tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_APP_BILLING)){
            return placeOrderAdminCallbackService.billingOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderAdminCallbackService.goodsOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        //商家端门票与App订单退款
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderAdminCallbackService.ticketOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderAdminCallbackService.shoppingCartOrderUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }

        //设置APP用户一天之内用户退订的次数
        TbBizPlaceRuleExample tbBizPlaceRuleExample = new TbBizPlaceRuleExample();
        TbBizPlaceRuleExample.Criteria tbBizPlaceRuleCriteria = tbBizPlaceRuleExample.createCriteria();
        tbBizPlaceRuleCriteria.andPlaceIdEqualTo(reqOrderOperate.getPlaceId());
        List<TbBizPlaceRule> tbBizPlaceRuleList =  tbBizPlaceRuleMapper.selectByExample(tbBizPlaceRuleExample);
        Map<String, String> placeOrderRuleMap = baseService.getPlaceOrderRule();
        int PLACE_PLAN_MAX_REFUND = 0;
        int PLACE_UNSUBSCRIBE_TIME = 0;
        PLACE_PLAN_MAX_REFUND = Integer.parseInt(placeOrderRuleMap.get("MAX_REFUND_ORDER_NUM"));//一天最大退订次数
        if(CollectionUtils.isEmpty(tbBizPlaceRuleList)){
            PLACE_UNSUBSCRIBE_TIME = PlaceConstants.PLACE_UNSUBSCRIBE_TIME;
            logger.info("订单退款验证规则从默认配置中获取，placeId={}",reqOrderOperate.getPlaceId());
        }
        else {
            TbBizPlaceRule tbBizPlaceRule = tbBizPlaceRuleList.get(0);
            PLACE_UNSUBSCRIBE_TIME = tbBizPlaceRule.getUnsubscribeTime();//提前退订小时数
        }

        if(PlaceConstants.ORDER_OPERATE_APPUSER.equals(reqOrderOperate.getUserType())){

            TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
            TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
            tbBizPlaceOrderCriteria.andUidEqualTo(reqOrderOperate.getUid());
            tbBizPlaceOrderCriteria.andOrderStatusChangeDateEqualTo(new Date());
            List<Byte> values = new ArrayList<>();
            values.add(PlaceConstants.ORDER_REFUNDING_STATUS);
            values.add(PlaceConstants.ORDER_REFUND_STATUS);
            tbBizPlaceOrderCriteria.andOrderStatusIn(values);
            tbBizPlaceOrderCriteria.andPayStatusNotEqualTo(PlaceConstants.REFUNDING_EXCEPTION_STATUS);
            List<TbBizPlaceOrder> placeOrderList = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
            if(CollectionUtils.isNotEmpty(placeOrderList)){
                if (placeOrderList.size() >= PLACE_PLAN_MAX_REFUND) {
                    return APIResponse.returnFail("您一天之内已经退订"+PLACE_PLAN_MAX_REFUND +"次，不能再退订场地！");
                }
            }
        }


        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)){
            if(PlaceConstants.ORDER_PAYED_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){
                //判断退款条件是否成立
                APIResponse apiResponseRefund = isRefund(placeOrderSalePlanList);
                if(apiResponseRefund != null){
                    return apiResponseRefund;
                }
                try {
                    if(PLACE_UNSUBSCRIBE_TIME == 0){
                        return APIResponse.returnFail("本场馆不支持退订");
                    }
                   String startTime = placeOrderSalePlanList.get(0).getStartTime();
                    String startDate = placeOrderSalePlanList.get(0).getDate();
                    Date date = DateUtils.dateStrToDate(startDate + " " + startTime);
                    if(PlaceConstants.ORDER_OPERATE_ADMINUSER.equals(reqOrderOperate.getUserType())){
                        if(System.currentTimeMillis() >= date.getTime()){
                            return APIResponse.returnFail("您已经超过退订时间，不能退订！");
                        }
                    }
                    else {
                        int length = DateUtils.dateDiffHour(new Date(),date);//销售计划日期减去当前日期
                        if(length < PLACE_UNSUBSCRIBE_TIME ){//已经小于开场前24小时，不能退订
                            return APIResponse.returnFail("仅支持开场前" + PLACE_UNSUBSCRIBE_TIME + "小时退订，您已经超过退订时间，不能退订！");
                        }
                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }

                APIResponse<RespUserInfoBase> userMsg = null;
                try {
                    userMsg = userServiceFacade.queryUserInfo(reqOrderOperate.getUid());
                    if(!userMsg.isRet()){
                        return APIResponse.returnFail("调用用户系统异常");

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return APIResponse.returnFail("调用用户系统异常");
                }

                RespUserInfoBase respUserInfoBase = userMsg.getData();
                reqOrderOperate.setName(respUserInfoBase.getNickName());

                //TODO 通知订单系统，退款处理，传入旧的的订单号，获取订单系统退款订单号


                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                List<TbBizPlacePayItem> tbBizPlacePayItemList = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
                if(CollectionUtils.isEmpty(tbBizPlacePayItemList)){
                    return APIResponse.returnFail("不存在订单信息！");
                }


                for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    //判断是否为卡支付
                    //与场馆原老板结算的老会员支付方式做特殊处理
                    if(PlaceConstants.PAY_WAY_FOR_CARD.equals(tbBizPlacePayItem.getPayType())
                            || PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS.equals(tbBizPlacePayItem.getPayType().toString())){
                        return orderCardPayUnsubscribeOperate(reqOrderOperate,placeOrderSalePlanList);
                    }
                    //判断是否只使用优惠券支付
                    if(PlaceConstants.PAY_WAY_FOR_COUPON.equals(tbBizPlacePayItem.getPayType()) && tbBizPlacePayItemList.size() == 1 ){
                        return APIResponse.returnFail("只使用优惠券支付，不允许退款。");
                    }
                }

                APIRequest<ReqOrderRefund> orderRefundAPIRequest = new APIRequest<>();
                ReqOrderRefund reqOrderRefund = new ReqOrderRefund();
                reqOrderRefund.setSourceBusinessId(Constants.PLACE_BOOKING_CODE);
                reqOrderRefund.setSourceSystemId(Constants.PLACE_SYSTEM_CODE);
                reqOrderRefund.setOrderNo(placeOrderSalePlanList.get(0).getOrderNo());
                reqOrderRefund.setReason(reqOrderOperate.getReason());
                reqOrderRefund.setUid(reqOrderOperate.getUid());
                //reqOrderRefund.setRefundNotifyURL(refundUrl);
                reqOrderRefund.setRefundNotifyURL("");
                reqOrderRefund.setNeedAudit(false); //false不需要人工审核.  true: 需要人工审核, 根据业务需求设置
                reqOrderRefund.setOutTradeNo(reqOrderOperate.getOrderNo());
                reqOrderRefund.setOutTradeRefundNo(reqOrderOperate.getOrderNo());//业务系统退款流水号，目前为订单号
                reqOrderRefund.setVer(reqOrderOperate.getVer());
                //查询销售计划表
                List<ReqRefundProduct> reqRefundProducts = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    ReqRefundProduct refundProduct = new ReqRefundProduct();
                    refundProduct.setPrice(placeOrderSalePlan.getPrice());
                    refundProduct.setProductId(placeOrderSalePlan.getSaleId());
                    refundProduct.setQuantity(1);
                    refundProduct.setProductName(placeOrderSalePlan.getStartTime() + "-" + placeOrderSalePlan.getEndTime()+"时段");
                    reqRefundProducts.add(refundProduct);
                }

                reqOrderRefund.setRefundProductList(reqRefundProducts);


                List<ReqRefundPayInfo> reqRefundPayInfoList = new ArrayList<ReqRefundPayInfo>();
                List<Integer>  payTypeList = PlaceOrderUtil.getPayType();
                for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    ReqRefundPayInfo  reqRefundPayInfo = new ReqRefundPayInfo();
                    reqRefundPayInfo.setPayId(tbBizPlacePayItem.getPayType());
                    reqRefundPayInfo.setRefundAmount(tbBizPlacePayItem.getAmount());
                    if(payTypeList.contains(reqRefundPayInfo.getPayId())){
                        reqOrderRefund.setAmount(tbBizPlacePayItem.getAmount());//TODO 累加
                    }

                    reqRefundPayInfoList.add(reqRefundPayInfo);

                }
                reqOrderRefund.setReqRefundPayInfos(reqRefundPayInfoList);
                orderRefundAPIRequest.setData(reqOrderRefund);
                APIResponse<RefundStatusEnum> apiResponse = null;
                try {
                    logger.info("申请退款参数："+JSON.toJSONString(reqOrderRefund));
                    apiResponse = this.orderPayService.refundApply(orderRefundAPIRequest);
                } catch (Exception e) {
                    logger.warn("申请退款异常："+e.getMessage());
                    e.printStackTrace();

                }
                if (null == apiResponse){
                    return APIResponse.returnFail("订单退款受理失败，请重试！");
                } else if (!apiResponse.isRet()){
                    logger.warn("订单退款受理失败，orderNo：{}，errMsg：{}",reqOrderOperate.getOrderNo(),apiResponse.getErrmsg());
                    return apiResponse;
                }

                TbBizPlaceOrderExample tbBizPlaceOrderExample1 = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria1 = tbBizPlaceOrderExample1.createCriteria();
                tbBizPlaceOrderCriteria1.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                TbBizPlaceOrder tbBizPlaceRecord = new TbBizPlaceOrder();
                tbBizPlaceRecord.setOrderStatus(PlaceConstants.ORDER_REFUNDING_STATUS);
                tbBizPlaceRecord.setOrderStatusChangeDate(new Date());

                tbBizPlaceOrderMapper.updateByExampleSelective(tbBizPlaceRecord, tbBizPlaceOrderExample1);

                //释放库存
                ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
                reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
                reqPlaceOrderListVo.setUid(null);//清理uid
                reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
                List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
                for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
                    UnitSalePlan unitSalePlan = new UnitSalePlan();
                    unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
                    unitSalePlanIdList.add(unitSalePlan);
                }
                reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
                placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);


                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter1 = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter1 != null && parameter1.getParameterValue() != null) {
                    if (Integer.valueOf(parameter1.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }

                //发送mq消息给运动场业务
                /*PlaceOrderVo placeOrderVo = new PlaceOrderVo();
                placeOrderVo.setUid(reqOrderOperate.getUid());
                placeOrderVo.setPlaceOrderId(reqOrderOperate.getOrderNo());
                placeOrderVo.setType(2);
                mqPlaceProductWrapper.sendOrderInfoToStadium(placeOrderVo);*/

                //TODO 插入退款表

                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());

                //加入消息推送，提示订场成功
                /*PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(2);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setName(respUserInfoBase.getNickName());
                placeMessage.setCurrTime(DateUtils.transferDateToStringZHCN(new Date()));
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                placeMessage.setServicePhone(parameter.getParameterValue());
                boolean result = pushMessageOperate(placeMessage);*/

                //加入消息推送，app端申请退款推送
                PlaceMessage placeMessage = new PlaceMessage();
                placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
                placeMessage.setOrderType(2);
                List<Integer> uids = new ArrayList<>();
                uids.add(reqOrderOperate.getUid());
                placeMessage.setUids(uids);
                String salePlanDate = placeOrderSalePlanList.get(0).getDate();
                String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
                placeMessage.setDate(salePlanDateNew);
                placeMessage.setPlaceName(tbBizPlace.getName());
                placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
                placeMessage.setName(reqOrderOperate.getName());
                placeMessage.setCurrTime(DateUtils.transferDateToStringEN(new Date()));
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                placeMessage.setServicePhone(parameter.getParameterValue());
                boolean result = pushMessageOperate(placeMessage);
                //加入消息队列进行异步消息推送处理
                if(!result){
                    mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
                }
                //封装插入历史记录
                ReqPlaceOrderInfo reqPlaceOrderInfo = new ReqPlaceOrderInfo();
                reqPlaceOrderInfo.setPlaceOrderId(reqOrderOperate.getOrderNo());
                List<ReqPayInfo> reqPayInfos = new ArrayList<>();
                for (TbBizPlacePayItem tbBizPlacePayItem : tbBizPlacePayItemList) {
                    ReqPayInfo reqPayInfo = new ReqPayInfo();
                    reqPayInfo.setPayId(tbBizPlacePayItem.getPayType());
                    reqPayInfos.add(reqPayInfo);
                }
                reqPlaceOrderInfo.setPayInfos(reqPayInfos);
                //insertOrderRecordHistory(reqOrderOperate);//1：退款

                return APIResponse.returnSuccess("订单退款受理成功！");
            }
            else if(PlaceConstants.ORDER_REFUNDING_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())){
                return APIResponse.returnFail("订单退款已经受理！");
            }
            else {
                logger.warn("订单退款处理异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单退款处理异常！");
            }
        }
        return APIResponse.returnFail("不存在该退款订单！");
    }


    /**
     * 判断是否可以退款
     * @param placeOrderSalePlanList
     * @return
     */
    private APIResponse isRefund(List<PlaceOrderSalePlan> placeOrderSalePlanList){
        //门票不允许退款
        if(placeOrderSalePlanList.get(0).getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return APIResponse.returnFail("门票不允许退款。");
        }

        //达人使用过的订单不允许退款
        if(placeOrderSalePlanList.get(0).getOrderUse() == 2){
            return APIResponse.returnFail("该订单已经使用，不允许退款。");
        }

        //包场订单根据EnableRefund字段判断是否可以退订
        if(placeOrderSalePlanList.get(0).getUseType().equals(PlaceConstants.ORDER_USE_BLOCK_BOOKING)  && placeOrderSalePlanList.get(0).getEnableRefund() == 0){
            return APIResponse.returnFail("该包场订单不允许退款。");
        }

        return null;
    }

    /**
     * 会员卡和优惠券支付 只退会员卡金额 即 订单金额-减优惠券 = 退款金额
     * @param placeOrderId
     * @return
     */
    private TbBizPlacePayItem getPayItem(String placeOrderId){
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        tbBizPlacePayItemCriteria.andPayTypeEqualTo(PlaceConstants.PAY_WAY_FOR_CARD);//会员卡支付
        List<TbBizPlacePayItem> placePayItem = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
        if (!org.springframework.util.CollectionUtils.isEmpty(placePayItem)){
            return placePayItem.get(0);
        }
        return null;
    }

    /**
     * 获取订单支付方式
     * @param placeOrderId
     * @return
     */
    private List<TbBizPlacePayItem> placePayItemSize(String placeOrderId){
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(placeOrderId);
        List<TbBizPlacePayItem> placePayItem = tbBizPlacePayItemMapper.selectByExample(tbBizPlacePayItemExample);
        if (!org.springframework.util.CollectionUtils.isEmpty(placePayItem)){
            return placePayItem;
        }
        return null;
    }

    /**
     * 会员卡退款处理
     * @param reqOrderOperate
     * @param placeOrderSalePlanList
     * @return
     */

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse orderCardPayUnsubscribeOperate(ReqOrderOperate reqOrderOperate,List<PlaceOrderSalePlan> placeOrderSalePlanList) {
        //根据订单号查询使用的会员卡
        TbBizPlaceMemberOpHistoryExample  tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
        TbBizPlaceMemberOpHistoryExample.Criteria tbBizPlaceMemberOpHistoryCriteria = tbBizPlaceMemberOpHistoryExample.createCriteria();
        tbBizPlaceMemberOpHistoryCriteria.andOrderNoEqualTo(reqOrderOperate.getOrderNo());
        List<TbBizPlaceMemberOpHistory> tbBizPlaceMemberOpHistoryList = tbBizPlaceMemberOpHistoryMapper.selectByExample(tbBizPlaceMemberOpHistoryExample);

        if(CollectionUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
            return APIResponse.returnFail("不存在该订单信息！");
        }
        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistoryTemp = tbBizPlaceMemberOpHistoryList.get(0);
        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getPlaceMemberCardInfo(tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo(),reqOrderOperate.getPlaceId(),reqOrderOperate.getUid());

        //设置订单状态和支付状态为已经退款状态
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

        TbBizPlaceOrder record = new TbBizPlaceOrder();
        record.setPayStatus(PlaceConstants.REFUNDING_STATUS);
        record.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
        Date date = new Date();
        record.setOrderStatusChangeDate(date);
        record.setRefundTime(date);
        record.setEndTime(date);

        List<TbBizPlacePayItem> paySize = placePayItemSize(reqOrderOperate.getOrderNo());
        if (null != paySize && paySize.size() >0){
            //用会员卡支付
            if (paySize.size() == 1){
                record.setCredit(placeOrderSalePlanList.get(0).getDebit());
            }else{
                //用会员卡和优惠券支付 仅退会员卡支付金额
                TbBizPlacePayItem payItem = getPayItem( reqOrderOperate.getOrderNo());
                if (null != payItem){
                    record.setCredit(payItem.getAmount());
                }
            }
        }
        //record.setCredit(placeOrderSalePlanList.get(0).getDebit());
        tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

        //更改订单支付明细的状态为退款状态
        TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
        tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
        TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
        TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
        tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
        tbBizPlacePayItemCriteria.andPayTypeEqualTo(PlaceConstants.PAY_WAY_FOR_CARD);//会员卡支付
        tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem, tbBizPlacePayItemExample);

        //释放库存
        ReqPlaceOrderListVo reqPlaceOrderListVo = new ReqPlaceOrderListVo();
        reqPlaceOrderListVo.setStatus(PlaceConstants.PLACE_PREORDER_STATUS);
        reqPlaceOrderListVo.setUid(null);//清理uid
        reqPlaceOrderListVo.setLockTime(null);//清理锁表时间
        List<UnitSalePlan> unitSalePlanIdList = new ArrayList<>();
        for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
            UnitSalePlan unitSalePlan = new UnitSalePlan();
            unitSalePlan.setSaleId(placeOrderSalePlan.getSaleId());
            unitSalePlanIdList.add(unitSalePlan);
        }
        reqPlaceOrderListVo.setUnitSalePlanIdList(unitSalePlanIdList);
        placeOrderService.updateSalePlanByPrimaryKeyList(reqPlaceOrderListVo);

        //增加订单金额
        TbBizPlaceMemberCardExample tbBizPlaceMemberCardExample = new TbBizPlaceMemberCardExample();
        TbBizPlaceMemberCardExample.Criteria tbBizPlaceMemberCardCriteria = tbBizPlaceMemberCardExample.createCriteria();
        tbBizPlaceMemberCardCriteria.andInnerCardNoEqualTo(tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo());
        TbBizPlaceMemberCard tbBizPlaceMemberCardAfter = new TbBizPlaceMemberCard();

        TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();

        //如果为储值赠送卡，加上本金金额以及赠送金额
        if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal surplusAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterAmount());
            BigDecimal surplusGiveAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterGiveAmount());
            tbBizPlaceMemberCardAfter.setSurplusAmount(surplusAmount.add(tbBizPlaceMemberCard.getSurplusAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
            tbBizPlaceMemberCardAfter.setSurplusGiveAmount(surplusGiveAmount.add(tbBizPlaceMemberCard.getSurplusGiveAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));

        }
        //如果为储值折扣卡直接加上本金金额
        else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal surplusAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterAmount());
            tbBizPlaceMemberCardAfter.setSurplusGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
            tbBizPlaceMemberCardAfter.setSurplusAmount(surplusAmount.add(tbBizPlaceMemberCard.getSurplusAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
        }
        //储值赠送折扣卡处理，加上本金金额以及赠送金额
        else if(PlaceConstants.PLACE_MEMBER_CARD_TYPE_VALUE_DISCOUNT.equals(tbBizPlaceMemberCard.getCardType())){
            BigDecimal surplusAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterAmount());
            BigDecimal surplusGiveAmount = tbBizPlaceMemberOpHistoryTemp.getOpBeforeGiveAmount().subtract(tbBizPlaceMemberOpHistoryTemp.getOpAfterGiveAmount());
            tbBizPlaceMemberCardAfter.setSurplusAmount(surplusAmount.add(tbBizPlaceMemberCard.getSurplusAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));
            tbBizPlaceMemberCardAfter.setSurplusGiveAmount(surplusGiveAmount.add(tbBizPlaceMemberCard.getSurplusGiveAmount()).setScale(2,BigDecimal.ROUND_HALF_UP));

        }

        placeMemberService.updatePlaceMemberCardInfo(tbBizPlaceMemberCardExample,tbBizPlaceMemberCardAfter);

        //获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqOrderOperate.getUid());
        //获取流水号
        String no = CommonUtils.generateNo(reqOrderOperate.getPlaceId());
        //插入流水记录表
        tbBizPlaceMemberOpHistory.setNo(no);//传入流水号
        tbBizPlaceMemberOpHistory.setOrderNo(orderNo);//存入本次的订单号
        tbBizPlaceMemberOpHistory.setRefundNo(tbBizPlaceMemberOpHistoryList.get(0).getOrderNo());//存入需要退款的订单号
        tbBizPlaceMemberOpHistory.setUid(reqOrderOperate.getUid());
        tbBizPlaceMemberOpHistory.setUserName(tbBizPlaceMemberOpHistoryList.get(0).getUserName());
        tbBizPlaceMemberOpHistory.setMobile(tbBizPlaceMemberOpHistoryList.get(0).getMobile());
        tbBizPlaceMemberOpHistory.setInnerCardNo(tbBizPlaceMemberOpHistoryList.get(0).getInnerCardNo());
        tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard.getCardName());
        tbBizPlaceMemberOpHistory.setAmount(tbBizPlaceMemberOpHistoryTemp.getAmount());
        String opTypeName = tbBizPlaceMemberOpHistoryList.get(0).getOpTypeName();
        tbBizPlaceMemberOpHistory.setOpTypeName(opTypeName + "退款");
        tbBizPlaceMemberOpHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount());
        tbBizPlaceMemberOpHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
        tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCardAfter.getSurplusAmount());
        tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCardAfter.getSurplusGiveAmount());
        tbBizPlaceMemberOpHistory.setPlaceId(reqOrderOperate.getPlaceId());
        tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_REFUND);
        tbBizPlaceMemberOpHistory.setSourceType(tbBizPlaceMemberOpHistoryList.get(0).getSourceType());
        tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        tbBizPlaceMemberOpHistory.setOpBeforeNumbers(0);
        tbBizPlaceMemberOpHistory.setOpAfterNumbers(0);
        tbBizPlaceMemberOpHistory.setMemo("会员卡退款");
        tbBizPlaceMemberOpHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
        tbBizPlaceMemberOpHistory.setCreateUid(reqOrderOperate.getUid());
        tbBizPlaceMemberOpHistory.setPayType(PlaceConstants.PAY_WAY_FOR_CARD);
        tbBizPlaceMemberOpHistory.setPlatform(reqOrderOperate.getPlatformType());
        tbBizPlaceMemberOpHistoryMapper.insertSelective(tbBizPlaceMemberOpHistory);

        //场馆报名人数减一
        Map<String,Object> map = new HashMap<>();
        map.put("placeId", placeOrderSalePlanList.get(0).getPlaceId());
        map.put("subtractSignupCount", 1);
        placeMapper.updateCount(map);

        TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());
        /*try {
            this.searchService.addPlaceIndex(tbBizPlace, null);
        } catch (Exception e) {
            logger.error("增加索引失败，加入消息队列进行处理!");
            //加入消息队列进行异步处理
            TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
            tbBizPlaceVo.setTbBizPlace(tbBizPlace);
            mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
        }*/

        //加入消息推送，提示订场成功
        PlaceMessage placeMessage = new PlaceMessage();
        placeMessage.setOrderNo(reqOrderOperate.getOrderNo());
        placeMessage.setOrderType(2);
        List<Integer> uids = new ArrayList<>();
        uids.add(reqOrderOperate.getUid());
        placeMessage.setUids(uids);
        String salePlanDate = placeOrderSalePlanList.get(0).getDate();
        String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
        placeMessage.setDate(salePlanDateNew);
        placeMessage.setPlaceName(tbBizPlace.getName());
        placeMessage.setPlaceId(placeOrderSalePlanList.get(0).getPlaceId());
        placeMessage.setName(reqOrderOperate.getName());
        placeMessage.setCurrTime(DateUtils.transferDateToStringZHCN(new Date()));
        TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
        placeMessage.setServicePhone(parameter.getParameterValue());
        boolean result = pushMessageOperate(placeMessage);
        //加入消息队列进行异步消息推送处理
        if(!result){
            mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
        }

        //退款发送短信
        smsRefundSendOperate(placeOrderSalePlanList,reqOrderOperate.getUid(),tbBizPlace);
        /**会员卡退款**/
        orderCallBackHistory(reqOrderOperate);

        return APIResponse.returnSuccess("订单退款成功！");

    }


    /**
     * 如果支付系统完成退款，消息队列订阅到，进行订单处理
     * @param reqOrderOperate
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse<?> orderCompleteUnsubscribeOperate(ReqOrderOperate reqOrderOperate) {
        //需要进行权限控制，不能让外部系统调用
        if(reqOrderOperate.getOrderOperateKey() == null || !PlaceConstants.ORDER_OPERATE_KEY.equals(reqOrderOperate.getOrderOperateKey())){
            return APIResponse.returnFail("没有调用权限！");
        }
        Map<String,Object> queryMap = new HashMap<>();
        queryMap.put("orderNo", reqOrderOperate.getOrderNo());
        queryMap.put("uid", reqOrderOperate.getUid());
        TbBizPlaceOrder tbBizPlaceOrder = getBizPlaceOrder(reqOrderOperate.getOrderNo());

        if (tbBizPlaceOrder==null){
            String childrenOrderNo = reqOrderOperate.getRefundOrderNo();//退款订单为子订单
            TbBizPlaceOrder childrenOrder = getBizPlaceOrderForBookAll(childrenOrderNo);
            if (childrenOrder == null){
                return APIResponse.returnFail("没有该条订单信息！");
            }
            //包场退款完成回调
            return placeOrderAdminCallbackService.bookAllOrderCompleteUnsubscribeOperate(reqOrderOperate,childrenOrder);
        }

        /*if (tbBizPlaceOrder.getSourceType().intValue() == PlaceConstants.SOURCE_TYPE_MEMBERCARD.intValue()){
            return placeMemberWrapper.orderCompleteUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
        }*/
        //商家端扫码开单回调
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_BILLING)){
            return placeOrderAdminCallbackService.billingOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_GOODS)){
            return placeOrderAdminCallbackService.goodsOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        //商家端对线上门票订单退款
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_TICKET)){
            return placeOrderAdminCallbackService.ticketOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }
        if (tbBizPlaceOrder.getUseType().equals(PlaceConstants.ORDER_USE_SHOPPING_CART)){
            return placeOrderAdminCallbackService.shoppingCartOrderCompleteUnsubscribeOperate(reqOrderOperate,tbBizPlaceOrder);
        }

        List<PlaceOrderSalePlan> placeOrderSalePlanList = tbBizPlaceOrderManagerMapper.selectOrderStatus(queryMap);
        if(CollectionUtils.isNotEmpty(placeOrderSalePlanList)) {
            if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                TbBizPlaceOrder record = new TbBizPlaceOrder();
                //设置支付状态
                if (reqOrderOperate.getExceptionFlag()){
                    record.setPayStatus(PlaceConstants.REFUNDING_EXCEPTION_STATUS);
                }
                else {
                    record.setPayStatus(PlaceConstants.REFUNDING_STATUS);
                }

                //设置订单状态和支付状态为已经退款状态
                TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
                TbBizPlaceOrderExample.Criteria tbBizPlaceOrderCriteria = tbBizPlaceOrderExample.createCriteria();
                tbBizPlaceOrderCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());

                record.setOrderStatus(PlaceConstants.ORDER_REFUND_STATUS);
                Date date = new Date();
                record.setOrderStatusChangeDate(date);
                record.setRefundTime(date);
                record.setEndTime(date);
                record.setCredit(placeOrderSalePlanList.get(0).getDebit());
                tbBizPlaceOrderMapper.updateByExampleSelective(record, tbBizPlaceOrderExample);

                //更改订单支付明细的状态为退款状态
                TbBizPlacePayItem tbBizPlacePayItem = new TbBizPlacePayItem();
                tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
                TbBizPlacePayItemExample tbBizPlacePayItemExample = new TbBizPlacePayItemExample();
                TbBizPlacePayItemExample.Criteria tbBizPlacePayItemCriteria = tbBizPlacePayItemExample.createCriteria();
                tbBizPlacePayItemCriteria.andPlaceOrderIdEqualTo(reqOrderOperate.getOrderNo());
                tbBizPlacePayItemMapper.updateByExampleSelective(tbBizPlacePayItem, tbBizPlacePayItemExample);

                /**设置服务开关
                 * ServiceSwitch 0:不支持，1:支持
                 * **/
                TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.PLACE_CONTAIN_VIP.getCode());
                if (parameter != null && parameter.getParameterValue() != null) {
                    if (Integer.valueOf(parameter.getParameterValue()).equals(1)){
                        OrderItemCostDTO orderItemCostDTO = new OrderItemCostDTO();
                        orderItemCostDTO.setReqOrderOperate(reqOrderOperate);
                        APIResponse callBackOrderStatus = apiPlaceOrderService.callBackOrderStatus(orderItemCostDTO);
                        if (callBackOrderStatus != null){
                            APIResponse.returnFail("更新订单状态异常");
                        }
                    }
                }

                //场馆报名人数减一
                Map<String,Object> map = new HashMap<>();
                map.put("placeId", placeOrderSalePlanList.get(0).getPlaceId());
                map.put("subtractSignupCount", 1);
                placeMapper.updateCount(map);

                TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(placeOrderSalePlanList.get(0).getPlaceId());
                /*try {
                    this.searchService.addPlaceIndex(tbBizPlace, null);
                } catch (Exception e) {
                    logger.error("增加索引失败，加入消息队列进行处理!");
                    //加入消息队列进行异步处理
                    TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
                    tbBizPlaceVo.setTbBizPlace(tbBizPlace);
                    mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
                }*/
                /**商家端退款**/
                orderCallBackHistory(reqOrderOperate);

                //发送退款短信
                smsRefundSendOperate(placeOrderSalePlanList, reqOrderOperate.getUid(),tbBizPlace);

                return APIResponse.returnSuccess("订单退款成功！");
            } else if (PlaceConstants.ORDER_REFUND_STATUS.equals(placeOrderSalePlanList.get(0).getOrderStatus())) {
                return APIResponse.returnSuccess("订单退款已经成功！");
            }
            else {
                logger.warn("订单退款异常，订单号：{} 订单当前状态：{}",reqOrderOperate.getOrderNo(),placeOrderSalePlanList.get(0).getOrderStatus());
                return APIResponse.returnFail("订单退款异常！");
            }

        }

        return APIResponse.returnFail("不存在该退款订单！");

    }


    /**
     * 消息推送
     * @param placeMessage
     * @return
     */
    private boolean pushMessageOperate(PlaceMessage placeMessage) {
        ReqPushMessage reqPushMessage = new ReqPushMessage();
        PushMessage pushMessage = new PushMessage();
        pushMessage.setTag(BoxName.ORDER.value() + System.currentTimeMillis());
        pushMessage.setTo(placeMessage.getUids());                          //下单用户的uid
        pushMessage.setLogo(Constants.LARK_LOGO);
        pushMessage.setLogoUrl("");
        Payload payload = new Payload();
        String body = "";
        String title = "";
        String payType = "";
        NewBody newBody = null;
        /**orderType:1 App订场，2 App退款 4: 购买门票**/
        if(placeMessage.getOrderType() == 1){
            title = "场地预订提醒";
            body = "您已成功预订" + placeMessage.getDate() + placeMessage.getPlaceName() + "的" +placeMessage.getCategoryValue()+ "场地。";
        }
        else if(placeMessage.getOrderType() == 2){
            //title = "尊敬的" +placeMessage.getName()+"，您于" +placeMessage.getCurrTime() + "申请"+ placeMessage.getPlaceName() + "退订业务已成功，退款将于三个工作日内返还。有疑问请致电" + placeMessage.getServicePhone();
            title = "场地退款提醒";
            newBody = getNewBody(placeMessage);
            payload.setNewBody(newBody);
        }
        else if(placeMessage.getOrderType() == 3){

            if(placeMessage.getPayType() == 1){
                payType = "支付宝";
            }
            else if(placeMessage.getPayType() == 2 || placeMessage.getPayType() == 3){
                payType = "微信";
            }
            body="很抱歉，您的订单支付异常，系统将在2个工作日内退回已支付款项，具体到账时间以" +payType + "处理为准。如有需要，可重新下单。";
        }
        if(placeMessage.getOrderType() == 4){
            title = "场地门票购买提醒";
            int count = placeTicketService.getTicketSaleCountByOrderNo(placeMessage.getOrderNo());
            body = "您已成功购买" + placeMessage.getDate() + placeMessage.getPlaceName() + "的" +placeMessage.getCategoryValue()+ "门票"+ count +"张。";
        }
        if (placeMessage.getOrderType() == 2){//app端退款
            payload.setMsgType(MsgType.ORDER_MSG.value());//订单 5
        }else{
            payload.setMsgType(MsgType.JUMP_MSG.value());
        }

        Alert alert = new Alert();
        alert.setTitle("场馆订单");
        pushMessage.setAlert(alert);
        alert.setBody(title);
        payload.setTitle(title);
        payload.setBody(body);
        payload.setBoxType(BoxType.PLACE_ORDER_MSG.value());
        payload.setUrl("/api/place/shops/orderDetail");
        Jump jump = new Jump();
        jump.setIdType(IdType.PLACE_ORDER_DETAIL_PAGE.value());
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("orderNo",placeMessage.getOrderNo());
        jump.setParam(param);
        payload.setJump(jump);
        payload.setTimestamp(System.currentTimeMillis());
        pushMessage.setPayload(payload);
        reqPushMessage.setMsgList(Arrays.asList(pushMessage));

        try {
            String postJson = JSON.toJSONString(reqPushMessage);
            logger.info("---------推送消息：" + postJson);
            String result = HttpClientUtils.postJson(cAddress + "/push/NewMsg.api", postJson);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String errcode = jsonObject.getString("errcode");
            logger.info("---------推送返回：" + result);
            if(errcode != null && errcode.equals("200")){
                return true;
            }
        } catch (Exception e) {
            logger.info("推送消息失败，" + e.getMessage());
        }
        return false;

    }


    private NewBody getNewBody(PlaceMessage placeMessage){
        NewBody newBody = new NewBody();
        newBody.setB("");
        newBody.setbColor("");

        Map<String, Object> map = new HashMap<>();
        List<String> list = new ArrayList<>();
        list.add(placeMessage.getOrderNo());
        map.put("placeOrderId",list);
        BigDecimal payAmount = financeCommonManagerMapper.getOrderDiscountAmount(map);
        List<Entry> entries = new ArrayList<>();
        Entry entry = new Entry();
        entry.setKey("退款金额");
        entry.setValue(payAmount.toString()+"元");
        entry.setKcolor("#ed4d4d");
        entry.setVcolor("#ed4d4d");
        entries.add(entry);

        Entry entry1 = new Entry();
        entry1.setKey("场馆名称");
        entry1.setValue(placeMessage.getPlaceName());
        entry1.setKcolor("");
        entry1.setVcolor("");
        entries.add(entry1);

        Entry entry2 = new Entry();
        entry2.setKey("申请时间");
        entry2.setValue(DateUtils.transferLongToDateStrings(System.currentTimeMillis()));
        entry2.setKcolor("");
        entry2.setVcolor("");
        entries.add(entry2);

        Entry entry3 = new Entry();
        entry3.setKey("到账时间");
        entry3.setValue("三个工作日内");
        entry3.setKcolor("");
        entry3.setVcolor("");
        entries.add(entry3);

        newBody.setEntries(entries);
       return newBody;
    }
   

    /**
     * 记录订单回调
     * @param orderOperate
     */
    @Async
    public void orderCallBackHistory(ReqOrderOperate orderOperate) {
        OrderHistoryDTO orderHistoryDTO = new OrderHistoryDTO();
        orderHistoryDTO.setReqOrderOperate(orderOperate);
        /**是退款 还是支付成功**/
        orderHistoryDTO.setOrderType(orderOperate.getOperateType());
        apiPlaceOrderService.insertOrderHistory(orderHistoryDTO);
    }

    
   


    /**
     * 会员卡支付成功回调
     * @param reqPlaceOrderInfo
     * @param tbBizPlaceUnitSalePlanList
     * @return
     *//*

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    private APIResponse paySuccessOperate(ReqPlaceOrderInfo reqPlaceOrderInfo,List<TbBizPlaceUnitSalePlan> tbBizPlaceUnitSalePlanList){
        //馆报名人数加一
        Map<String,Object> map = new HashMap<>();
        map.put("placeId", reqPlaceOrderInfo.getPlaceId());
        map.put("addSignupCount", 1);
        placeMapper.updateCount(map);

        TbBizPlace tbBizPlace = this.tbBizPlaceMapper.selectByPrimaryKey(reqPlaceOrderInfo.getPlaceId());

        //加入消息推送，提示订场成功
        PlaceMessage placeMessage = new PlaceMessage();
        placeMessage.setOrderNo(reqPlaceOrderInfo.getOrderNo());
        placeMessage.setOrderType(1);
        List<Integer> uids = new ArrayList<>();
        uids.add(reqPlaceOrderInfo.getUid());
        placeMessage.setUids(uids);
        String salePlanDate = DateUtils.transferDateToString(tbBizPlaceUnitSalePlanList.get(0).getDate());
        String salePlanDateNew = DateUtils.tranferStringToZHCN(salePlanDate);
        placeMessage.setDate(salePlanDateNew);
        placeMessage.setPlaceName(tbBizPlace.getName());
        placeMessage.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        placeMessage.setPayType(PlaceConstants.PAY_WAY_FOR_CARD);
        Cagetory cagetory =cagetoryMapper.selectByPrimaryKey(reqPlaceOrderInfo.getCategoryId());
        placeMessage.setCategoryValue(cagetory.getName());
        boolean result = pushMessageOperate(placeMessage);
        //加入消息队列进行异步消息推送处理
        if(!result){
            mqPlaceProductWrapper.pushMessageAsyncSend(placeMessage);
        }

        //发送短信
        smsSendOperate(null,tbBizPlaceUnitSalePlanList,reqPlaceOrderInfo.getUid(),tbBizPlace);
        ReqOrderOperate orderOperate = new ReqOrderOperate();
        orderOperate.setOperateType(2); //订单完成
        orderOperate.setOrderNo(reqPlaceOrderInfo.getOrderNo());
        orderOperate.setPlatformType(reqPlaceOrderInfo.getPlatformType());
        orderOperate.setPlaceId(reqPlaceOrderInfo.getPlaceId());
        *//**会员卡支付成功回调**//*
        orderCallBackHistory(orderOperate);
        try {
            this.searchService.addPlaceIndex(tbBizPlace, null);
        } catch (Exception e) {
            logger.error("增加索引失败，加入消息队列进行处理!");
            //加入消息队列进行异步索引添加处理
            TbBizPlaceVo tbBizPlaceVo = new TbBizPlaceVo();
            tbBizPlaceVo.setTbBizPlace(tbBizPlace);
            mqPlaceProductWrapper.addPlaceIndexAsyncSend(tbBizPlaceVo);
        }
        return APIResponse.returnSuccess();

    }*/



    /**
     * 购买门票成功后短信推送
     * @param placeTicketPushOrderVo
     * @param uid
     * @param tbBizPlace
     * @return
     */
    @Async
    private boolean ticketSmsSendOperate(PlaceTicketPushOrderVo placeTicketPushOrderVo,Integer uid, TbBizPlace tbBizPlace){
        if(null == placeTicketPushOrderVo){
            return false;
        }
        List<String> mobiles=new ArrayList<>();
        List<String> params=new ArrayList<>();
        String phone="";
        String [] args = new String[3];
        args[0] = "";
        args[1] = "";
        args[2] = "";
        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            phone=placeAttach.getBookingConsultPhone();
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            phone=parameterVo!=null?parameterVo.getParameterValue():"";
        }


        String salePlanDateNew = placeTicketPushOrderVo.getDate();

        args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + placeTicketPushOrderVo.getCategoryId().toString());
        List<TicketPushOrderVo> pushOrderVos = placeTicketPushOrderVo.getTicketPushOrderVos();
        if (!org.springframework.util.CollectionUtils.isEmpty(pushOrderVos)){
            for (TicketPushOrderVo TicketPushOrderVo : pushOrderVos) {
                args[1] +=TicketPushOrderVo.getTicketName() + " " + DateTimeUtils.timeToStr(TicketPushOrderVo.getStartTime()) + "-" + DateTimeUtils.timeToStr(TicketPushOrderVo.getEndTime()) + "、";
            }
        }
        args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";
        args[2] = phone;


        APIResponse<RespUserInfoBase> userMsg = userServiceFacade.queryUserInfo(uid);
        if(!userMsg.isRet()){
            return false;
        }
        RespUserInfoBase respUserInfoBase = userMsg.getData();
        mobiles.add(respUserInfoBase.getMobile());
        params.addAll(Arrays.asList(args));
        try {
          //placeTicketService.asyncSendSms(respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_TICKET_NOTICE,args,true);
            placeSmsService.sendSms(mobiles,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_TICKET_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,params);
        } catch(Exception e){
            logger.info("短信发送失败-------->" + e.getMessage());
            return false;
        }

        //发送短信提醒给场馆人员
        /*
        TbBizPlaceNoticeMobile messageVo = placeMessageService.getMobileDataByPlaceId(tbBizPlace.getId());
        if (null!=messageVo){
            APIResponse<RespUserInfoBase> resPvo = userServiceFacade.queryUserInfo(uid);
            List<String> mobileList=new ArrayList<>();
            List<String> paramList=new ArrayList<>();
            String[] messageArgs = new String[3];
            messageArgs[0] = resPvo != null ? resPvo.getData().getMobile() : "";
            messageArgs[1]=args[0];
            messageArgs[2]=args[1];
            mobileList.add(messageVo.getMobile());
            paramList.addAll(Arrays.asList(messageArgs));
            try {
                if (!StringUtils.isEmpty(messageVo.getMobile())){
                    //placeTicketService.asyncSendSmsToOperator(messageVo.getMobile(),respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_REMIND, messageArgs, true);
                    placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_ORDER_REMIND, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
                }
            } catch (java.lang.Exception e) {
                logger.info("短信发送失败-------->" + e.getMessage());
            }
        }
        */
        return true;
    }



    /**
     * 商品订单退款
     * @param tbBizPlaceOrderItems
     * @param tbBizPlaceOrder
     * @param tbBizPlacePayItems
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private TbBizPlaceOrder goodsOrderRefund(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
                                             TbBizPlaceOrder tbBizPlaceOrder,
                                             List<TbBizPlacePayItem> tbBizPlacePayItems) throws Exception{

        TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);
        TbBizPlaceOrderItem tbBizPlaceOrderItem = tbBizPlaceOrderItems.get(0);

        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItem.getPayType().toString())
                || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItem.getPayType().toString())){
            /**  扫码退款 **/
            tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
        }
        if (PlaceConstants.ORDER_REFUND_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
                || PlaceConstants.REFUNDING_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
            tbBizPlacePayItem.setAmountType(PlaceConstants.CREDIT_TYPE);
            int flag = tbBizPlacePayItemMapper.updateByPrimaryKeySelective(tbBizPlacePayItem);
            if (flag !=1 ){
                throw new Exception("商品退款修改支付明细异常");
            }
            //释放库存
            placeGoodsService.addGoodsInventory(tbBizPlaceOrder,tbBizPlaceOrderItems);
        }
        if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
            //退款中，释放库存
            placeGoodsService.addGoodsInventory(tbBizPlaceOrder, tbBizPlaceOrderItems);

        }
        return tbBizPlaceOrder;
    }

    /**
     * 开单包场散客退款
     * @param tbBizPlaceOrderItems
     * @param tbBizPlaceOrder
     * @param tbBizPlacePayItems
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    private TbBizPlaceOrder billingAndBlockOrderRefund(List<TbBizPlaceOrderItem> tbBizPlaceOrderItems,
                                                       TbBizPlaceOrder tbBizPlaceOrder,
                                                       List<TbBizPlacePayItem> tbBizPlacePayItems) throws Exception{
        TbBizPlacePayItem tbBizPlacePayItem = tbBizPlacePayItems.get(0);
        TbBizPlaceOrderItem tbBizPlaceOrderItem = tbBizPlaceOrderItems.get(0);
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_WXSCAN.equals(tbBizPlacePayItem.getPayType().toString())
                || PlaceConstants.PLACE_ADMIN_PAY_WAYS_ALISCAN.equals(tbBizPlacePayItem.getPayType().toString())){
            /**  扫码退款 **/
            if (tbBizPlaceOrder.getUseType().byteValue() == PlaceConstants.ORDER_USE_BLOCK_BOOKING) {
                //包场退款
                TbBizPlacePrivateOrder tbBizPlacePrivateOrder = tbBizPlacePrivateOrderMapper
                        .selectByPrimaryKey(tbBizPlaceOrder.getParentId());
                //针对包场订单部分付款（包场未成功，在开单处再进行支付）情况
                if (tbBizPlacePrivateOrder.getPayStatus().intValue() != PlaceConstants.PAY_STATUS.intValue()
                        && tbBizPlacePrivateOrder.getOrderStatus().intValue() != PlaceConstants.ORDER_PAYED_STATUS){
                    tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
                }else if (!StringUtils.isEmpty(tbBizPlaceOrder.getOrderNo())){
                    //兼容 包场预订再用扫码枪支付情况
                    tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
                }else{
                    //从父订单拿到下单信息（将父订单拆成多个子订单进行退款）
                    String childrenOrderId = tbBizPlaceOrder.getPlaceOrderId();//记录订单订单号，退款完重置子订单的订单号
                    //将父订单的退款依据给子订单
                    tbBizPlaceOrder.setOrderNo(tbBizPlacePrivateOrder.getOrderNo());
                    tbBizPlaceOrder.setPlaceOrderId(tbBizPlacePrivateOrder.getPlaceOrderId());

                    tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,childrenOrderId);

                    tbBizPlaceOrder.setPlaceOrderId(childrenOrderId);//退款完重置子订单的订单号
                }
            }else{
                tbBizPlaceOrder = placeOrderService.placeScanRefund(tbBizPlaceOrder,tbBizPlacePayItems,tbBizPlaceOrderItems,null);
            }
        }
        if (PlaceConstants.ORDER_REFUND_STATUS.equals(tbBizPlaceOrder.getOrderStatus())
                || PlaceConstants.REFUNDING_STATUS.equals(tbBizPlaceOrder.getPayStatus())){
            //已退款，释放库存
            ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
            reqOrderOperate.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());

            placeOrderService.refundUpdateUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_PREORDER_STATUS);

        }
        if (PlaceConstants.ORDER_REFUNDING_STATUS.equals(tbBizPlaceOrder.getOrderStatus())){
            //退款中，(需要锁定场地库存)释放库存
            ReqOrderOperate reqOrderOperate = new ReqOrderOperate();
            reqOrderOperate.setOrderNo(tbBizPlaceOrder.getPlaceOrderId());

            placeOrderService.refundUpdateUnitSalePlan(tbBizPlaceOrderItems,PlaceConstants.PLACE_PREORDER_STATUS);

        }
        return tbBizPlaceOrder;
    }

    /**
     * 退场短信发送
     * @param placeOrderSalePlanList
     * @param uid
     * @param tbBizPlace
     * @return
     */
    @Async
    private boolean smsRefundSendOperate(List<PlaceOrderSalePlan> placeOrderSalePlanList,Integer uid, TbBizPlace tbBizPlace){
        if(CollectionUtils.isEmpty(placeOrderSalePlanList) ){
            return false;
        }
        List<String> mobileList=new ArrayList<>();
        List<String> paramList=new ArrayList<>();
        String [] args = new String[3];
        args[0] = "";
        args[1] = "";
        args[2] = "";

        Comparator<PlaceOrderSalePlan> comparator = new Comparator<PlaceOrderSalePlan>() {
            @Override
            public int compare(PlaceOrderSalePlan o1, PlaceOrderSalePlan o2) {
                return o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName()) == 0 ? o1.getStartTime().compareTo(o2.getStartTime()) : o1.getPlaceUnitName().compareTo(o2.getPlaceUnitName());

            }
        };
        Collections.sort(placeOrderSalePlanList, comparator);

        String salePlanDateNew = DateUtils.tranferStringToZHCN(placeOrderSalePlanList.get(0).getDate());
        args[0] = salePlanDateNew + tbBizPlace.getName() + "的" + iBaseService.getCommonDataCache("cagetory" + placeOrderSalePlanList.get(0).getCategoryId().toString());
        for (PlaceOrderSalePlan placeOrderSalePlan : placeOrderSalePlanList) {
            String startTime = placeOrderSalePlan.getStartTime();
            String endTime = placeOrderSalePlan.getEndTime();
            args[1] +=placeOrderSalePlan.getPlaceUnitName() + " " +  startTime.substring(0,startTime.length()-3) + "-" + endTime.substring(0,endTime.length()-3) + "、";
        }
        args[1] = "[" + args[1].substring(0,args[1].length()-1) + "]";

        //TbCommonParameter parameter = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
        //args[2] = parameter.getParameterValue();
        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlace.getId());
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            args[2]=placeAttach.getBookingConsultPhone();
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            args[2]=parameterVo!=null?parameterVo.getParameterValue():"";
        }

        APIResponse<RespUserInfoBase> userMsg = userServiceFacade.queryUserInfo(uid);
        if(!userMsg.isRet()){
            return false;
        }
        RespUserInfoBase respUserInfoBase = userMsg.getData();

        mobileList.add(respUserInfoBase.getMobile());
        paramList.addAll(Arrays.asList(args));
        //Result result = smsService.sendMessageToPhone(respUserInfoBase.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE,args,true);
        placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_REFUND_NOTICE, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
        return true;
    }

    /**
     * 获取订单信息
     * @return
     */
    private TbBizPlaceOrder getBizPlaceOrder(String orderNo){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        tbBizPlaceOrderExampleCriteria.andIsEffectiveEqualTo((byte)1);//TODO 是否有效
        List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    /**
     * 包场获取子订单信息
     * @return
     */
    private TbBizPlaceOrder getBizPlaceOrderForBookAll(String orderNo){
        TbBizPlaceOrderExample tbBizPlaceOrderExample = new TbBizPlaceOrderExample();
        TbBizPlaceOrderExample.Criteria tbBizPlaceOrderExampleCriteria = tbBizPlaceOrderExample.createCriteria();
        tbBizPlaceOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        List<TbBizPlaceOrder> selectByExample = tbBizPlaceOrderMapper.selectByExample(tbBizPlaceOrderExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    /**
     * 获取包场父订单信息
     * @return
     */
    private TbBizPlacePrivateOrder getBizPlacePrivateOrder(String orderNo){
        TbBizPlacePrivateOrderExample tbBizPlacePrivateOrderExample = new TbBizPlacePrivateOrderExample();
        TbBizPlacePrivateOrderExample.Criteria tbBizPlacePrivateOrderExampleCriteria = tbBizPlacePrivateOrderExample.createCriteria();
        tbBizPlacePrivateOrderExampleCriteria.andPlaceOrderIdEqualTo(orderNo);
        List<TbBizPlacePrivateOrder> selectByExample = tbBizPlacePrivateOrderMapper.selectByExample(tbBizPlacePrivateOrderExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    /**
     * 获取会员卡充值信息
     * @return
     */
    private TbBizPlaceMemberOpHistory getBizPlaceMemberHistory(String orderNo){
        TbBizPlaceMemberOpHistoryExample tbBizPlaceMemberOpHistoryExample = new TbBizPlaceMemberOpHistoryExample();
        tbBizPlaceMemberOpHistoryExample.createCriteria().andOrderNoEqualTo(orderNo);
        //tbBizPlaceMemberOpHistoryExample.setOrderByClause(" id for update ");//加锁
        List<TbBizPlaceMemberOpHistory> selectByExample  = tbBizPlaceMemberOpHistoryMapper
                .selectByExample(tbBizPlaceMemberOpHistoryExample);
        return !selectByExample.isEmpty()?selectByExample.get(0):null;
    }

    public  boolean getCombineSubSalePlanList(Integer placeId, TbBizPlaceUnitSalePlan combineSalePlan, List<TbBizPlaceUnitSalePlan> subSalePlanList)  {
        boolean valid = false;

        Byte unitType = combineSalePlan.getUnitType();
        if (unitType != null && UNIT_TYPE_BASE.equals(unitType)) {
            valid = false;
        } else {
            String subSaleplans = combineSalePlan.getSubSaleplans();
            if (subSaleplans == null || subSaleplans.isEmpty()) {
                TbBizPlaceUnitSalePlan tbCSP = null;
                if (combineSalePlan.getId() != null) {
                    tbCSP = puspMapper.selectByPrimaryKey(combineSalePlan.getId());
                } else if (combineSalePlan.getSaleId() != null) {
                    TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
                    TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
                    criteria.andPlaceIdEqualTo(placeId);
                    criteria.andSaleIdEqualTo(combineSalePlan.getSaleId());

                    List<TbBizPlaceUnitSalePlan> pusps = puspMapper.selectByExample(example);
                    if (pusps != null && pusps.size() > 0) {
                        tbCSP = pusps.get(0);
                    }
                }

                if (tbCSP != null) {
                    subSaleplans = tbCSP.getSubSaleplans();
                }
            }

            List<String> subSaleplanIds = new ArrayList<>();
            if (subSaleplans != null) {
                subSaleplanIds = Arrays.asList(subSaleplans.split("[|]"));
            }

            // 从数据库中读取
            if (subSaleplanIds.size() > 0) {
                TbBizPlaceUnitSalePlanExample example = new TbBizPlaceUnitSalePlanExample();
                TbBizPlaceUnitSalePlanExample.Criteria criteria = example.createCriteria();
                criteria.andPlaceIdEqualTo(placeId);
                criteria.andSaleIdIn(subSaleplanIds);
                List<TbBizPlaceUnitSalePlan> temp = puspMapper.selectByExample(example);
                if (temp != null) {
                    subSalePlanList.addAll(temp);
                }

                if (subSaleplanIds != null && subSalePlanList.size() == subSaleplanIds.size()) {
                    valid = true;
                }
            }
        }

        return valid;
    }

}
